如何在Twig中将变量从父模板传递到子模板? [英] How can I pass variable from parent template to child template in Twig?

查看:51
本文介绍了如何在Twig中将变量从父模板传递到子模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Symfony和Twig合作,但找不到下一个问题的解决方案:在我的父模板( index.html.twig )中,我有这样的代码:

I'm working with Symfony and Twig and I can't find solution for the next problem: in my parent template (index.html.twig) I have such code:

<noscript>
    {% block noscript %}
    <div class="alert alert-warning">
        <strong>{% block notice %}{{ notice_js_disabled }}{% endblock %}&nbsp;</strong>
        {% block message %}{{ js_disabled }}{% endblock %}
    </div>
    {% endblock %}
</noscript>

我有子模板( category.html.twig ),该子模板扩展了 index.html.twig 模板.

I have child template (category.html.twig) which extends index.html.twig template.

我可以从索引模板到类别模板传递 {{notice_js_disabled}} var的值吗?
从我的Symfony indexAction 控制器返回了 notice_js_disabled .

Can I pass value of {{ notice_js_disabled }} var from index template to category template?
notice_js_disabled is returned from my Symfony indexAction controller.

UPD:接下来,为我建立的问题提供了解决方案:我制作了名为main.html.twig的基本模板,在其中从控制器渲染元素:

UPD: The solution for my problem I founded, next: I have made base templae, called main.html.twig, where I'm rendering element from the controller:

{% block header %}
   {{ render(controller('StoreBundle:Header:index')) }}
{% endblock %}

然后,在我的index.html.twig文件上,进行以下操作:

Then, on my index.html.twig file, I made next things:

{% extends 'Store/tpl/main.html.twig' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
    <p class="currentPage" hidden>home</p>
    {{ parent() }}
{% endblock %}

我不确定这是否是正确的解决方案,但这是可行的:)

I'm not sure is it correct solution, but it's work:)

推荐答案

您需要执行的操作如下:-在父模板中创建一个变量

What you have to do is the following: -Create A variable in the parent template

{% set notice_js_disabled = value_received_from_indexAction %}

在需要该值的模板之后

{{ notice_js_disabled }}

希望对您有帮助

这篇关于如何在Twig中将变量从父模板传递到子模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆