I'm looking for a way to inject a feature flag variable so that it is accessible in all Twig templates, but I can't figure out how to do it. I've tried adding variables in preprocessing hooks in my .theme file, but this doesn't seem to do to the trick. For example:

function mytheme_preprocess_page(&$variables) {
  $variables['some_feature_flag'] = 'test_value';

function mytheme_preprocess_html(&$variables) {
  $variables['some_feature_flag'] = 'test_value;

My template for the node contains {{dump(some_feature_flag)}}, which evaluates to NULL. I can't find a way to get this working.

  • did you replace mytheme with the actual name of your theme?
    – No Sssweat
    Commented Jun 2, 2017 at 21:43

2 Answers 2


So generally, preprocess hooks impact the specific theme item or template, so hook_preprocess_page() impacts the page.html.twig and hook_preprocess_html() does so for html.html.twig. You mentioned your twig template for node, to add variables to that you would need to implement hook_preprocess_node().

Your question was adding variables to all templates, I believe for that you would use just hook_preprocess() (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_preprocess/8.2.x) - though I have never tried it. I imagine it would be called for every theme call so that could create a lot of overhead.

And don't forget to 'Clear all caches' under admin->config->development->performance when you create new preprocess hooks or template files.


If you want to add a variable to every template used from a theme, without implementing more than one preprocess function, you can:

Keep in mind that hook_preprocess() is invoked for a theme only when that theme is used for rendering the current page. That doesn't happen for modules; so, if those variables you are trying to set should be available to more than one theme, then it would be better to implement one of those hooks in a module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.