Using Twig and Symfony2 to create a page title

In the layout, we check if a view has set the title block. If so, we use a hyphen to separate the view and the layout title. If not, we just use the layout’s title. You can extend the example to translate the layout title.

1 2 3 4 5 6 7 8 9 10 11 12
<!DOCTYPE html>
<html>
<head>
{% if block('title') %}
{% set title = block('title') ~ ' - My App' %}
{% else %}
{% set title = 'My App' %}
{% endif %}
<title>{{ title }}</title>
</head>
<body></body>
</html>

And in your view, you can set the title:

1 2 3 4 5
{% extends 'MyAppCoreBundle::layout.html.twig' %}
 
{% block title %}
{{ 'my_app.core.view.somewhere.something.title'|trans }}{{ parent() }}
{% endblock %}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>