简体   繁体   English

如何在树枝模板文件中定义全局变量?

[英]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.是否可以在 twig 文件中设置全局变量,以便我可以从其他文件、宏和块中访问该变量。

For example, I want to have variables.twig file and in it set my variables and then I can include it in other templates.例如,我想要variables.twig文件并在其中设置我的变量,然后我可以将它包含在其他模板中。

I know that setting global variables is possible from the framework (eg Symfony) but I want a solution using twig features only.我知道可以从框架(例如 Symfony)设置全局变量,但我想要一个仅使用 twig 功能的解决方案。

Using Symfony configuration使用 Symfony 配置

If you are using Symfony2+, you can set globals in your config.yml file:如果你使用 Symfony2+,你可以在你的config.yml文件中设置全局变量:

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

And then use {{ myStuff }} anywhere in your application.然后在应用程序的任何地方使用{{ myStuff }}


Using Twig_Environment::addGlobal使用 Twig_Environment::addGlobal

If you are using Twig in another project, you can set your globals directly in the environment:如果你在另一个项目中使用 Twig,你可以直接在环境中设置你的全局变量:

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

And then use {{ myStuff }} anywhere in your application.然后在应用程序的任何地方使用{{ myStuff }}


Using a Twig template使用 Twig 模板

When you're including a piece of Twig code, you're only including the rendered view coming from that code, not the code itself.当您包含一段 Twig 代码时,您只包含来自该代码的渲染视图,而不是代码本身。 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 .Symfony 4开始,您可以在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.似乎您可以在顶级模板中分配全局 READONLY 变量并在所有底层模板中使用它们。 But you can't override them of course.但是你当然不能覆盖它们。 It covers my case, maybe will be useful for somebody else.它涵盖了我的情况,也许对其他人有用。

base.html.twig 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 my_page.twig

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

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

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

deep.twig deep.twig

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

Using SlimFramework and Twig-View:3.0使用SlimFrameworkTwig-View:3.0

You can use the following method Twig::offsetSet您可以使用以下方法Twig::offsetSet

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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