[英]How to populate up variables from included twig template
I want to be able to populate up variables from included twig templates, just like when you're extending another template. 我希望能够从包含的树枝模板中填充变量,就像在扩展另一个模板时一样。 Here's an example:
这是一个例子:
I have base.twig as follows: 我有base.twig如下:
{# base.twig #}
<html>
<head></head>
<body class="body {{class_from_index}}">
<nav>...</nav>
{% block content %}
{% endblock %}
<footer>...</footer>
</body>
</html>
and index.twig as follows: 和index.twig如下:
{# index.twig #}
{% extends "base.twig" %}
{% set class_from_index = 'index' }
{% block content %}
<div>My actual content</div>
{% endblock %}
doing like this, the variable class_from_index
is populated to base.twig
, when I'm rendering index.twig
. 做这样的变量
class_from_index
填充到base.twig
,当我渲染index.twig
。 However if i have gallery.twig like this: 但是,如果我有像这样的gallery.twig:
{# gallery.twig #}
{% set class_from_index = 'gallery' %}
<div>
A gallery
</div>
and adding {% include gallery.twig %}
in index.twig
, the variable class_from_index
is not populated up to index.twig
or base.twig
. 并在
index.twig
添加{% include gallery.twig %}
,变量class_from_index
不会填充到index.twig
或base.twig
。 I know that if gallery.twig
extends index.twig
and index.twig
extends base.twig
, this will work, but this is not the case. 我知道,如果
gallery.twig
扩展index.twig
和index.twig
扩展base.twig
,这将起作用,但事实并非如此。
Is there a way to achieve what I'm trying to explain? 有没有办法实现我要解释的内容? Thank you :)
谢谢 :)
If main.twig contains: 如果main.twig包含:
{% include "gallery.twig" %}
The compiled result will be: 编译结果将是:
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->loadTemplate("gallery.twig", "main.twig", 1)->display($context);
}
And if gallery.twig contains: 并且如果gallery.twig包含:
{% set var = 42 %}
The result is: 结果是:
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["var"] = 42;
}
As you can see, the context is not given as a reference, so your variable can't be populated. 如您所见,上下文没有作为参考,因此您的变量无法填充。
The reason is quite obvious. 原因很明显。 It looks very exotic to use variables from a lower scope to a upper one.
从较低范围到较高范围使用变量看起来很奇怪。 That's like if you were doing in PHP:
就像您使用PHP一样:
<?php
function gallery() {
$var = 42;
}
gallery();
echo $var;
There must be a better solution to your problem... by designing your templates architecture another way. 必须通过另一种方式设计模板架构,才能更好地解决您的问题。 The question itself is not relevant, that's totally out of good practices.
这个问题本身并不重要,完全是出于良好实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.