Hi,
How can I use dynamic global variables ?
I want to assign variable in a first template and use it in a second one.
Thanks
Hi,
if what you need is to pass a variable from a template twig to another can watch the file blog.html.twig where the variables blog, page and truncate are initialized to be used in the file blog_item.html. twig
In this case there is no need for global variables
thanks iusvar,
in your suggestion, you have to include first template in a second one.
Is there another way without any link between the 2 templates ?
Yes, you can set a variable in the site object then use it later.
In the first Twig template do something like this:
{% set site = {'my_custom_var':'foo'}|merge(site) %}
Then in the other template you will now have access to it:
<h1>{{ site.my_custom_var }}</h1>
A better approach is simply to pass the variable from one template to the next with this syntax:
{% include 'partials/my_other_template.html.twig' with {'my_custom_var':'foo'} %}
Thanks rhukster
In the first template, I try :
{% set site = {‘my_custom_var’:‘foo’}|merge(site) %}
or
{% set site = site | merge ({‘my_custom_var’:‘foo’}) %}
so
{{ site.my_custom_var }}
works in this first template, but is empty in second one.If I first assign my_custom_var in site.yaml, site.my_custom_var changes in first template, not in second one.
the SET twig command seems not to change global site variable.
The second approach do not suit because the 2 templates are independent and not included.
Not included? You mean they are not in the same process? If so none of these will work. You can’t set a variable at runtime from a twig template. These do not persist back to the filesystem or cache.
You really will need to write a plugin to achieve this. Something that actually sets the variable then writes it back to the filesystem, or rethink your strategy because this is just not a standard thing to do.