Most of us know, the ideal way of making a variable available in a specific twig file is to use hook_preprocess_HOOK. But what if we have a requirement that we need a kind of global variable that should be accessible in any twig file. So, that we are able to use it wherever we want to, without additional pain.
The best part of Drupal is, everything is possible. But at the same time, there is a trick, you always have more than one way of doing things. And now it's in your hands to pick up the best suitable performant way for your solution.
So, over here you have the following solutions (which I can instantly think for this problem statement):
- hook_preprocess - the generic preprocess hook
- Create twig function
Approach 1: hook_preprocess
This is very generic which allows you to play with variables being passed to any twig and you can add it conditionally as well. Checkout Drupal.org documentation for further usage.
Approach 2: Create twig function
Creating twig function allows you to call it from any twig template. Basically use it wherever you want. Most of the real world cases, I believe you can solve by this approach. The later one makes your variable accessible in all twig files which may or may not be required, while this approach gives you explicit control on where ever you want to use the variable.
Try to analyse the performance aspect of both and feel free to leave comment if you have any suggestion or question.
Comments