在包含中设置 Twig 变量并在之后使用它

rek*_*kam 6 php template-engine global-variables twig

假设您有一个包含另一个模板的树枝模板 (tplA.twig)

<p>Twig template A</p>

{% set test = "in tpl A" %}
<p>first, variable is: {{ test }}</p>

{% include "tplB.twig" %}
<p>and the variable is: {{ test }}</p>
Run Code Online (Sandbox Code Playgroud)

和包含的模板(tplB.twig)

<div>Content of tpl B</div>
{% set test = "now is tpl B" %}
Run Code Online (Sandbox Code Playgroud)

在包含的模板中设置/更改变量并在主模板中使用它的最佳方法是什么?如何使用全局变量?请注意,我不能使用块和扩展,而且我没有使用 Symfony。

非常感谢

编辑

真正的上下文是一个非常基本的多语言结构。对于一个页面,我有一个主模板:

<h1>{{ i18n('mainTitle') }}</h1>
<h2>current language (fr, en): {{ ln }}</h2>

<!-- here a list of photos, but not in a foreach loop -->
<div>
    <div>
        <img src="/same/for/all/languages-a.jpg" alt="localized A" />
        <span>localized A</span>
    </div>
    <div>
        <img src="/same/for/all/languages-b.jpg" alt="localized B" />
        <span>localized B</span>
    </div>
    <!-- etc. -->
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个很小的网站,所以我没有用数据库创建一个复杂的结构,我想在模板中管理所有这些东西。

问题是:如何显示正确的本地化字符串?我想到的是包含一个本地化的模板,以分离关注点。就像是:

<!-- before the photos list -->
{% include ln ~ '/photos-list.twig' %}
<!-- then the photos list -->
Run Code Online (Sandbox Code Playgroud)

在这个模板中,我会在正确的语言环境中设置所有变量,这样我就可以在我的照片列表中使用它们。(如我问题的第一部分所述)

请注意,我对所有其他页面都有这种结构。文本内容在locale文件夹中分离,每个页面都有一个主模板(再次,这是一个非常基本的个人网站)

我最后做的是在照片列表之前插入一个 hudge if语句。如果 locale 是fr,用法语文本设置变量,如果是en,用英文文本设置变量。

这就是诀窍,所以我可以接受^^

Geo*_*iev 1

为什么不移动{{ test }}in的第二个调用tplB(针对这个场合)?

<div>Content of tpl B</div> {% set test = "now is tpl B" %} <p>and the variable is: {{ test }}</p>