Use Twig Custom Set Variables From an Include

symfony, twig

Solution

I was just trying to do the same thing you were and came up with the following:

Created `snippets.twig` to maintain all these mini variables. In your case, you might call it `variables.twig`. In this file, I used a macro without any arguments. I was creating formatted entry date markup that I can use across all my templates and it looked like this:

{% macro entry_date() %}
<time datetime="{{post.post_date|date('m-d-Y')}}">{{post.post_date|date('F j, Y')}}</time>
{% endmacro %}

note that the parenthesis after the name declaration were imperative

In my main layout file, `layout.twig`, I referenced this macro via an import statement so it would be accessible in all child templates:

{% import "snippets.twig" as snippets %}
<!doctype html>
...

In my template files, I now have `snippets` accessible and can query it like any other variable:

{{ snippets.entry_date }}

UPDATE

This doesn't seem to correctly run code. If you're just storing static content, you should be good. You can also pass args to the macro so I imagine you could make some magic happen there but I haven't tried it.

Problem

I'm trying to include a twig file with a bunch of custom set variables and then use the variables in the multiple other template files. Similar to how including a PHP file works. I don't seem to have access to the variables set inside the include in my index file. Is there any way to do this? Sample Code *Edited Included File: ``` {# variables.html #} {% set width = "100" %} {% set height = "250" %} ``` Template File: ``` {# index.html #} {% include 'variables.html' %} {{ width }} {{ height }} ``` Expected Outcome: ``` 100 250 ``` Actual Outcome: ``` // Nothing gets output ```

Original source