Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Dynamic global variable

Started by Muut Archive 11 years ago · 5 replies · 2033 views
11 years ago

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

11 years ago

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 :-)

11 years ago

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 ?

11 years ago

Yes, you can set a variable in the site object then use it later.

In the first Twig template do something like this:

TWIG
{% set site = {'my_custom_var':'foo'}|merge(site) %}

Then in the other template you will now have access to it:

TWIG
<h1>{{ site.my_custom_var }}</h1>

A better approach is simply to pass the variable from one template to the next with this syntax:

TWIG
{% include 'partials/my_other_template.html.twig' with {'my_custom_var':'foo'} %}
11 years ago

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
<h1>{{ site.my_custom_var }}</h1>
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.

11 years ago

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.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1349 9 years ago
Archive · by Muut Archive, 9 years ago
2 934 9 years ago
Archive · by Muut Archive, 9 years ago
2 4060 9 years ago
Archive · by Muut Archive, 9 years ago
1 2946 9 years ago
Archive · by Muut Archive, 9 years ago
3 1118 9 years ago