Aram Hayrapetyan
Aram Hayrapetyan

Reputation: 41

Twig how to check which template is geting rendered

I have

<div>
    <div id="page-wrapper" class="sidebar-content white-bg">
        <div class="row border-bottom">
            {% include '/layouts/navbar.html.twig' %}
        </div>

        {% block body %}{% endblock %}
    </div>
</div>

Now in this /layouts/navbar.html.twig theres an anchor tag, who's href attribute heavily depends on which template is rendered below, for example if its the Posts template, the href should be /posts/new, if its the announcements template, the href should be /announcements/newand so on, is that even possible?

Upvotes: 0

Views: 83

Answers (2)

igorshmigor
igorshmigor

Reputation: 802

If the path is the only thing that depends on the current template, I'd modify DarkBee's example to just simply pass the path from the parent template. That way you don't need the if/else structure:

posts.twig:

<div>
    <div id="page-wrapper" class="sidebar-content white-bg">
        <div class="row border-bottom">
            {% include "nav.twig" with { 'path': '/posts/new' } %}
        </div>

        {% block body %}{% endblock %}
    </div>
</div>

announcements.twig:

<div>
    <div id="page-wrapper" class="sidebar-content white-bg">
        <div class="row border-bottom">
            {% include "nav.twig" with { 'path': '/announcements/new' } %}
        </div>

        {% block body %}{% endblock %}
    </div>
</div>

nav.twig:

{% for i in 0..3 %}
    <a href="http://www.example.com/{{ path }}/{{ i }}">{{ i }}</a>
{% endfor %}

Upvotes: 0

DarkBee
DarkBee

Reputation: 15625

You could make use of the global variable _self to solve this e.g.

main.twig

{% include "foo.twig" %}
{% include "bar.twig" %}

foo.twig and bar.twig

<div>
    <div id="page-wrapper" class="sidebar-content white-bg">
        <div class="row border-bottom">
            {% include "nav.twig" with { 'template': _self, } %}
        </div>

        {% block body %}{% endblock %}
    </div>
</div>

nav.twig

{% set path = '' %}
{% if template == 'foo.twig' %}
    {% set path = 'path/to/foo' %}
{% elseif template == 'bar.twig' %}
    {% set path = 'path/to/bar' %}
{% endif %}

{% for i in 0..3 %}
<a href="http://www.example.com/{{ path }}/{{ i }}">{{ i }}</a>
{% endfor %}

demo

Upvotes: 1

Related Questions