How to pass variable from controller to twig template in Drupal-8? I have tried to pass variable on module theme folder, but I want to use this variable on global theme?


First create a function that returns the variable, something like this:

function my_function() {
return $var_name;

Then you must create a preprocess function, for the template, like this:

function MY_MODULE_preprocess_TEMPLATE(&$variables) {
  $V_NAME = my_function();
  $variables['v-name'] = $V_NAME;

Remember to clear the cache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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