Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the title of page dynamically with Twig

Tags:

twig

symfony

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>
like image 400
Nll Avatar asked Jun 27 '12 17:06

Nll


2 Answers

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> :-)

like image 59
Micronax Avatar answered Sep 19 '22 08:09

Micronax


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 %}`
like image 30
MDrollette Avatar answered Sep 18 '22 08:09

MDrollette