4

I have a Twig function in my theme that sets a random ID. The function works well if I include the entire function within any given template and then render the variable for that {{ randomID }} in the same template.

However, I'd like to be able to call this variable globally. I made an include file with the function and then call it in another Twig template like so:

  {% include directory ~ '/templates/slices/random_id.html.twig' with { randomID : 'randomID' } %}

... but now when I print {{ randomID }} in a given template where the include file is called, I do not see the random id print. I think I am on the right track here but not quite there yet.

I used these pages for reference:

  • I don't think the {{ randomID }} can be passed by {% include .... I guess you can pass the value in the alternative way. {% directory ~ '/templates/slices/random_id.html.twig' with 'randomID’: randomID %} – Jimmy Ko Aug 8 '16 at 9:45
  • If I just use directory, I get Unknown "directory" tag. If I stick with include directory, and update the syntax, it still does not seem to work but no errors. {% directory ~ '/templates/slices/random_id.html.twig' with {'randomID' : randomID} %} – Danny Englander Aug 8 '16 at 13:35
  • What about {% include '/templates/slices/random_id.html.twig' with randomID %} ? – Oana Hulpoi Aug 9 '16 at 8:20
  • @OanaHulpoi - yes I tried that according to twig.sensiolabs.org/doc/tags/include.html and it did not work either. – Danny Englander Aug 9 '16 at 23:52
  • 1
    Do you try create Twig function. You can see demo – MrD Aug 12 '16 at 2:35

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.