[英]Set Twig variable inside an include and use it afterward
imagine you have a twig template (tplA.twig) that include an other one 想象你有一个包含另一个的树枝模板(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>
and the included template (tplB.twig) 和包含的模板(tplB.twig)
<div>Content of tpl B</div>
{% set test = "now is tpl B" %}
What is the best way to set/change a variable in an included template and use it in the master template? 在包含的模板中设置/更改变量并在主模板中使用它的最佳方法是什么? How to use globals?
如何使用全局变量? Note that I can't use blocks and extends, and I'm not using Symfony.
请注意,我不能使用块和扩展,我不使用Symfony。
Many thanks 非常感谢
EDIT 编辑
The real context is a very basic multilingual structure. 真实的背景是一个非常基本的多语言结构。 For a page, I have one master template:
对于页面,我有一个主模板:
<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>
It is a very small website, so I didn't created a complex structure with database, and I wanted to manage all this stuff in the template. 这是一个非常小的网站,所以我没有用数据库创建一个复杂的结构,我想在模板中管理所有这些东西。
The thing is: how is it possible to display the right localized strings? 问题是:如何才能显示正确的本地化字符串? What I thought about was to include a localized template, to separate concerns.
我想到的是包含一个本地化的模板,以分离关注点。 Something like:
就像是:
<!-- before the photos list -->
{% include ln ~ '/photos-list.twig' %}
<!-- then the photos list -->
And inside this template, I would have setted all the variables in the right locale, so I could use them in my photos list. 在这个模板中,我会在正确的语言环境中设置所有变量,所以我可以在我的照片列表中使用它们。 (as explained in the first part of my question)
(正如我在问题的第一部分所解释的那样)
note that I have this structure for all others pages. 请注意,我对所有其他页面都有此结构。 Text content is separated in the locale folder, and each page has a master template (again, it's a very basic personal website)
文本内容在语言环境文件夹中分开,每个页面都有一个主模板(同样,它是一个非常基本的个人网站)
What I did finally was to insert a hudge if statement before the photos list. 我最后做的是在照片列表前插入一个hudge if语句。 If locale is fr , set variables with french texts, if it's en , set variables with english texts.
如果locale是fr ,则使用法语文本设置变量,如果是en ,则使用英语文本设置变量。
That does the trick, so I'm ok with that ^^ 这样做的伎俩,所以我很喜欢^^
你为什么不在tplB
移动{{ test }}
的第二次调用(对于这个场合)?
<div>Content of tpl B</div> {% set test = "now is tpl B" %} <p>and the variable is: {{ test }}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.