Skip to main content
PK's Diary

Main navigation

  • Home
  • Reposts
  • Stories
  • Articles
  • Notes
  • About

Breadcrumb

  1. Home
  2. Notes

Making a variable available (as global) in all twig files in Drupal

Twig global variable

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.

Tags

  • Drupal
  • Twig
  • Drupal Planet
References
Twig Functions Drupal
  • Log in to post comments

Comments

Explore topics

TwigQED42Acquia CertificationDrupal PlanetDrupal CertificationThinkingDrupalOpen SourceLifeBackend Specialist
more tags

Quick Notes

Accessing Translated Entity in Views Twig | Drupal 8
Making a variable available (as global) in all twig files in Drupal
Data Structures and Algorithms - Solved in Javascript | Geeksforgeeks
Create alias for frequently used commands
Acquia Front-End Specialist Exam Preparation Pointers

Recent Stories around me

Software Engineer Interview Experience with Glovo
Why Amazon is better than Flipkart - Indian ecommerce market
Acquia Certified Drupal 8 Grand Master
Seminar at DCRUST on Open Source as Career
A Walk to Remember | June 2015 - August 2018 | QED42

Recent write-ups | PK's pen

How to check if Memcache, opcache or varnish is functional with the Drupal 8 application?
Getting started with ReactJS & Drupal (Fully-Decoupled)
Extending Drupal Translations for Custom Entity in Drupal 7
Google Assistant Integration with Drupal
Art of writing template files - Drupal 8
PK's Diary
Powered by Drupal