简体   繁体   中英

How can I pass variable from parent template to child template in 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>

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

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: 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 %}

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 %}

After the template that you need that value

{{ notice_js_disabled }}

I hope it helps you

The only way in Twig you can pass some variable to a child template is by the include tag.

{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

However in this way you are not extending some parent template from the child, but you are doing the other way around: you are placing a submodule into the current template.

There are only a couple of variables which are global in symfony You can set some custom global variables in configuration like described here

Otherwise you can use some predefined global variables, the app variable. ( check it out here )

My personal advice is that you should review your application template logic.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM