doucai1901 2015-11-08 23:22
浏览 23
已采纳

如何填充包含的树枝模板中的变量

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 #}
<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 #}
{% 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. However if i have gallery.twig like this:

{# 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. I know that if gallery.twig extends index.twig and index.twig extends base.twig, this will work, but this is not the case.

Is there a way to achieve what I'm trying to explain? Thank you :)

  • 写回答

1条回答 默认 最新

  • douaoj0994 2015-11-09 08:14
    关注

    The problem

    If <kbd>main.twig</kbd> contains:

    {% 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 <kbd>gallery.twig</kbd> contains:

    {% 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 PHP equivalent

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大