Im using Twig for template in my website, I extend layout.html.twig
in all my others twig pages,so In my layout.html.twig
I have the title of page :
<title>{% block title %}Title of my website{% endblock %}</title>
Now my problem is how to change this title dynamically in all my pages, for example I have news.html.twig
to show all latest news in the world, so I hope when I display my news page I have the title of the news in my title of page...
<title>{% block title %}Title of the news{% endblock %}</title>
My solution looks a bit more elegant in the child-templates:
In your layout.html.twig
:
<title>{% if page_title is defined %} {{ page_title }} | {% endif %} Your Website</title>
In your child page-templates:
{% extends '::layout.html.twig' %}
{% set page_title = 'Your page-title' %}
{# Put the rest of your page below #}
And you can also reuse the title in eg. an doing <h1>{{ page_title }}</h1>
:-)
You are close. In your news.html.twig
I assume you have all of your content in a block like this:
{% extends '::layout.html.twig' %}
{% block content %}
content of the news page here
{% endblock %}`
So all you have to do is add another block for the title outside of that content block
{% extends '::layout.html.twig' %}
{% block title %}Title of news page{% endblock %}
{% block content %}
content of the news page here
{% endblock %}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With