Create a helper class and define in function in helper. Then you can use where ever in those Magento project.
Helpers are usually used as elements that are global and always available.
Magento 2 Helper contains functions and methods that are commonly used throughout the application. Methods that are declared as Helpers can be called from any template file, block, model, controller class
or even from another helper in Magento 2.
For more detail refer: https://www.mageplaza.com/devdocs/create-helper-class-magento-2.html
Updated solution:
you can get helper class valuea in template like below code
$this->helper('Vendor\Module\Helper\Data')->methodname();