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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀