在include中设置Twig变量,然后使用它


Set Twig variable inside an include and use it afterward

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

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

以及包含的模板(tplB.trick)

<div>Content of tpl B</div>
{% set test = "now is tpl B" %}

在包含的模板中设置/更改变量并在主模板中使用的最佳方式是什么?如何使用全局变量?请注意,我不能使用块和扩展,也没有使用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>

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

问题是:如何才能显示正确的本地化字符串?我想的是包括一个本地化的模板,以分离关注点。类似于:

<!-- before the photos list -->
{% include ln ~ '/photos-list.twig' %}
<!-- then the photos list -->

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

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

我最后做的是在照片列表之前插入一个hudgeif语句。如果语言环境是fr,则用法语文本设置变量;如果是en-则用英语文本设置变量。

这就成功了,所以我可以接受^^

为什么不在tplB中移动{{ test }}的第二个调用(针对这种情况)?

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

相关文章: