Adding a new region to a child Twig template

Last week, you learnt about extending a Twig template to make it easy to create variations of templates without duplicating code.

A reader followed up with this question:

If a need new region in front-template, I need to duplicate the system page-template ... or I have another solution?

So the question is, how do you add a new region to the child template (in this case, front-template is the child template)?

You can’t add something new to a child template, you can only replace a Twig block that exists in the parent. So this causes a problem, because in this case, we want to add a region to the child template only.

The solution is to include a Twig block in the parent that is empty. In affect, it acts as a placeholder for any child template to replace with whatever content you choose. An empty Twig block would look like this:

{% block hero %}{% endblock %}

In this case, I’m calling the block “hero”, but it could be anything.

And then in the child template, you can replace the hero block with the region of the same name (it could be any region):

{% block hero %}
  {% if page.hero %}
    {{ page.hero }}
  {% endif %}
{% endblock %} 

This is in effect the reverse of what we did last week, which was to replace a Twig block with content in it with any empty one.

Add region to child Twig template

The steps

Define the region if it doesn’t exist yet by adding it to your theme’s .info.yml file. In this example, I have added hero: Hero to the bottom of the regions.

regions:
  content: Content
  left: Left
  right: Right
  footer: Footer
  header: Header
  hero: Hero 

In your parent template (page.html.twig in this case), add a Twig block to act as a placeholder:

{% block hero %}{% endblock %}

Create a child template (page--front.html.twig in this case), if you haven’t already.

Extend the parent template and replace the empty Twig block with the new region:

{% extends "page.html.twig" %}
{% block hero %}
  {% if page.hero %}
    {{ page.hero }}
  {% endif %}
{% endblock %}

Clear the cache. And then add some content to the new region and it should appear where the child template is used (in this case, page--front.html.twg.

And that is all there is to it!

Add new comment