简体   繁体   中英

How can I define global variables inside a twig template file?

Is it possible to set global variables in a twig file, so that I can access that variables from other files, macros and blocks.

For example, I want to have variables.twig file and in it set my variables and then I can include it in other templates.

I know that setting global variables is possible from the framework (eg Symfony) but I want a solution using twig features only.

Using Symfony configuration

If you are using Symfony2+, you can set globals in your config.yml file:

# app/config/config.yml
twig:
    # ...
    globals:
        myStuff: %someParam%

And then use {{ myStuff }} anywhere in your application.


Using Twig_Environment::addGlobal

If you are using Twig in another project, you can set your globals directly in the environment:

$twig = new Twig_Environment($loader);
$twig->addGlobal('myStuff', $someVariable);

And then use {{ myStuff }} anywhere in your application.


Using a Twig template

When you're including a piece of Twig code, you're only including the rendered view coming from that code, not the code itself. So it is by design not possible to include a set of variables the way you are looking for.

Since Symfony 4 , you can set the globals in config/packages/twig.yaml .

# config/packages/twig.yaml
twig:
    # ...
    globals:
        ga_tracking: 'UA-xxxxx-x'

It seems that you can assign global READONLY variables in your top-level template and use them in all underlying templates. But you can't override them of course. It covers my case, maybe will be useful for somebody else.

base.html.twig

<!DOCTYPE html>
{# assign global vars here #}
{% set myReadonlyJar = your_custom_ext_twig_function() %} 
<html>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

my_page.twig

{% extends 'stack/base.html.twig' %}

{% block body %}
    {{ myReadonlyJar.v1 }}

    {{ myReadonlyJar.v2 }}
    {{ include('stack/deep.twig') }}
{% endblock %}

deep.twig

Check top vars very deep inside: <br>
{{ myReadonlyJar.v2 }}

Using SlimFramework and Twig-View:3.0

You can use the following method Twig::offsetSet

$twig = Twig::create('view/templates');
$twig->offsetSet('globalVar', 'globalVarValue');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM