php - Twig: How to set title in nested template blocks?

843

I have a twig structure like this:

{% extends '@layouts/default.html.twig' %}

{% block headerBar %}
    {% include 'partials/my-navigation.html.twig' %}
{% endblock %}

{% block content %}
    some content
{% endblock %}

But now I have always the same title in my "my-navigation.html.twig".

How can i make it dynamically? maybe something like this:

{% extends '@layouts/default.html.twig' %}

{% block myNiceTitle %}
    COOL TITLE 
{% endblock %}

{% block headerBar %}
    {% include 'partials/my-navigation.html.twig' %}
{% endblock %}

{% block content %}
    some content
{% endblock %}

and then i would use my title in the "my-navigation.html.twig" file dynamically? but how?

I have already read the manual here:

https://twig.symfony.com/doc/2.x/functions/block.html

but it doenst make me smarter :(

Thx for any hints

938

Answer

Solution:

Assuming thatmyNiceTitle is a block in your navigation template, you could useembed and do something like:

{% extends '@layouts/default.html.twig' %}

{% block headerBar %}
    {% embed 'partials/my-navigation.html.twig' %}  
        {% block myNiceTitle %}
            COOL TITLE 
        {% endblock %}
    {% endembed %}
{% endblock %}

{% block content %}
    some content
{% endblock %}

And somewhere inpartials/my-navigation.html.twig:

{% block myNiceTitle %}
    DEFAULT TITLE {# or nothing at all... #}
{% endblock %}
417

Answer

Solution:

Set a variable before the include

{% set title = 'COOL TITLE' %}

{% block headerBar %}
  {% include 'partials/my-navigation.html.twig' %}
{% endblock %}

Then use it inside your include

<title>{{ title }}</title>

People are also looking for solutions to the problem: php - Problem with deleting items from pivot table

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.