Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 62 ยท Templates with Twig

Layouts, Blocks and Includes

Share one page layout across your whole Symfony site with Twig template inheritance: extends, blocks, parent(), include, embed and macros, with a runnable demo.

Almost every page on a website has the same frame: a header, a navigation bar, a footer, a few stylesheets. Copying that frame into every template would make a redesign painful. Twig solves it with template inheritance: you write the frame once in a base template, mark the parts that may change as blocks, and every page template extends the base and fills in only its own blocks.

This lesson covers extends, block, parent(), include, embed and macros, which together remove nearly all repetition from templates. You should know the basics from Twig Basics. As before, real Twig appears in read-only code and the runnable examples use a small plain-PHP stand-in that follows the same rules.

The base layout

A new Symfony webapp project starts with templates/base.html.twig. A simplified version looks like this:

TWIG
{# templates/base.html.twig (real Twig, read-only) #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{% block title %}My shop{% endblock %}</title>
    {% block stylesheets %}{% endblock %}
</head>
<body>
    {% include 'partials/_navbar.html.twig' %}

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

    <footer>&copy; My shop</footer>
    {% block javascripts %}{% endblock %}
</body>
</html>

A block has a name and a default body (which may be empty). The base template defines where each block goes. It does not know which pages will override them.

Extending a layout

A child template starts with {% extends %} and then defines blocks. Anything outside a block in a child template is ignored, because the parent decides the structure.

TWIG
{# templates/product/index.html.twig (real Twig, read-only) #}
{% extends 'base.html.twig' %}

{% block title %}Products{% endblock %}

{% block body %}
    <h1>Our products</h1>
    {# ... list ... #}
{% endblock %}

extends must be the first tag in the child template. When Symfony renders product/index.html.twig, Twig finds the parent, renders it, and whenever the parent reaches a block, uses the child's version if there is one and the parent's own default otherwise.

parent(): add to a block instead of replacing it

Sometimes you want to extend a block's content, not replace it. The parent() function renders the block as defined in the parent template at that point:

TWIG
{# real Twig, read-only #}
{% block title %}{{ parent() }} | Products{% endblock %}

{% block stylesheets %}
    {{ parent() }}
    <link rel="stylesheet" href="{{ asset('css/products.css') }}">
{% endblock %}

With the base from above, the title becomes My shop | Products. A page keeps the shared styles and adds only its own. Without parent(), the child's block would replace the parent's body entirely.

Inheritance can be deeper than two levels. A section layout can extend base.html.twig and fill the body block with a sidebar that contains a new block, and individual pages extend the section layout. The same rule applies at every level: the most derived template wins, and parent() reaches one level up.

flowchart TB
    B["base.html.twig<br/>blocks: title, body"]
    S["layout/shop.html.twig<br/>extends base, adds sidebar,<br/>defines block content"]
    P["product/show.html.twig<br/>extends layout/shop, fills content"]
    P -->|extends| S
    S -->|extends| B

A page extends a section layout, which extends the base layout. Blocks defined lowest in the chain win.

Rendering blocks twice with block()

The block() function prints a block you have already defined, which is handy when a title must appear in both <title> and an <h1>:

TWIG
{# real Twig, read-only #}
{% block title %}Contact us{% endblock %}

{% block body %}
    <h1>{{ block('title') }}</h1>
{% endblock %}

A layout engine you can run

This stand-in resolves extends, block, parent(), include and a simple for loop. It keeps a chain of definitions for each block, with the most derived template first, and a parent() call steps one position along that chain. This is a simplified model of what Twig does when it compiles templates, but the rule it enforces is exactly the one you just learned.

PHP extends, block, parent() and include (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The home page keeps the default title, My shop. The products page used parent(), so its title is My shop | Products. The navigation bar is included once in the base and appears on both pages without being repeated.

Note: the {% include navbar %} in the stand-in omits the quotes to keep the code short; in real Twig you write {% include 'partials/_navbar.html.twig' %} with a quoted template name (or any expression that evaluates to a name).

include: reusable fragments

include renders another template in place and prints the result. It is the tool for small pieces that appear in many pages: a navbar, a product card, a pagination bar.

TWIG
{# real Twig, read-only #}
{% for product in products %}
    {% include 'product/_card.html.twig' %}
{% endfor %}

{# pass extra variables, and hide the current ones with "only" #}
{% include 'product/_card.html.twig' with {'product': featured, 'highlight': true} only %}

By default an included template sees every variable of the current template, including loop variables. with adds or overrides variables, and only restricts the included template to exactly those, which is the safer choice for reusable fragments because they cannot depend on hidden state. There is also an include() function, handy inside expressions: {{ include('partials/_flash.html.twig') }}.

A leading underscore in the file name (_card.html.twig) is a common convention for partials that are never rendered directly by a controller.

embed: include with overridable blocks

embed is a mix of include and extends. It includes a template, and lets you override its blocks at the point of use. It is useful for a generic component such as a card or a modal whose body differs between uses:

TWIG
{# real Twig, read-only #}
{% embed 'components/_card.html.twig' with {'title': 'Delivery'} %}
    {% block body %}Free shipping over $50.{% endblock %}
{% endembed %}

Use include when a fragment only needs data, and embed when callers need to inject whole chunks of markup.

Macros: functions inside templates

A macro is like a function written in Twig. It takes arguments and returns a string of markup, which is perfect for repetitive HTML such as form inputs or badges. Macros do not see the context of the calling template: they only know their own arguments, which makes them predictable.

TWIG
{# templates/macros/forms.html.twig (real Twig, read-only) #}
{% macro input(name, value = '', type = 'text') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
TWIG
{# real Twig, read-only #}
{% import 'macros/forms.html.twig' as forms %}

{{ forms.input('email', user.email, 'email') }}
{{ forms.input('city') }}

You can also pick single macros with {% from 'macros/forms.html.twig' import input %}, and macros defined in the same file are reachable through _self. Choose a macro when you repeat the same markup with different arguments, an include when the fragment needs the surrounding data.

Include inside loops

Fragments combine well with loops. The second stand-in builds a three-level chain (base, section layout, page) and renders a table whose rows come from an included template. It shows two things: deeper inheritance, and that an included template can read the loop variable of the including template.

PHP Three-level layout with an included row (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The page template fills content, which only exists in the section layout; the section layout fills body, which only exists in the base. The row template reads p, the loop variable of the including template, and the <A5> in the second product name comes out escaped.

Habits that keep layouts healthy

  • Keep the base layout small, with generously named blocks (title, stylesheets, body, javascripts). Adding a block later is cheap; removing one used by many pages is not.
  • Put things that appear on every page (flash messages, navigation) in the base and not in individual pages. See sessions and flash messages.
  • Prefer include ... only for reusable partials so that they declare their inputs explicitly.
  • Name the file by purpose: base.html.twig, layout/shop.html.twig, product/_card.html.twig.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a child template put at the very top?

    extends must be the first tag. The child then defines only the blocks it wants to change.
  2. 2. What does {{ parent() }} do inside a block?

    parent() outputs the block as defined one level up, which lets a child add to a shared block.
  3. 3. Which tag lets the caller override blocks of the template it includes?

    embed combines include and extends: it includes a template and lets you redefine its blocks at the point of use.
  4. 4. What is true about macros?

    A macro receives its inputs as arguments and does not see the caller's context, which makes it predictable.
  5. 5. What does the 'only' keyword do in {% include 'x.twig' with {'a': 1} only %}?

    only restricts the included template to the variables you pass explicitly.

Summary

  • A base template defines the page frame with named block areas; child templates extends it and override blocks.
  • parent() adds to a block's inherited content; block('name') prints a block again.
  • include renders a fragment (use with and only to control its variables); embed also lets callers override its blocks.
  • Macros are template functions for repeated markup, imported with import or from.
  • Inheritance can have many levels; the most derived template wins.

Next up: Twig Functions, Filters and Tests.