【问题标题】:Set Twig variable inside an include and use it afterward在包含中设置 Twig 变量并在之后使用它
【发布时间】:2014-10-17 10:03:50
【问题描述】:

假设您有一个树枝模板 (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>

和包含的模板(tplB.twig)

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

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

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

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

这就是诀窍,所以我没关系^^

【问题讨论】:

标签: php global-variables twig template-engine


【解决方案1】:

你为什么不把{{ test }} 的第二个电话移到tplB 中(为了这个场合)?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多