Extending/Including

Blocks

Blocks are used to define spaces that can be filled by child templates.  For example a template might look like this:

<html>
<body>
{% block content %}{% endblock content %}
</body>
</html>

Now a child can be created that extends this template. It can define a content block that will fill in the block above.

It is also possible to set a default, in case a child doesn't fill the block in:

<html>
<body>
{% block content %}
<h1>{{ this.title }}</h1>
{% endblock content %}
</body>
</html>

Now, if the child doesn't define a 'content' block, a default will be displayed. It is also possible to nest blocks:

<html>
<body>
{% block content %}
  <h1>{% block title %}{{ this.title }}{% endblock title %}</h1>
{% endblock content %}
</body>
</html>

Now a child template can define 'content' and override the whole thing, or 'title' and just replace the title area. It is also possible for the child to use {% parent %} to use the default in its defintion.

Extends

{% extends 'index.html' %}
{% block content %}
  <h1>{{ this.title }}</h1>
  {{ this.content }}
{% endblock content %}

Extending is one of the most important tools available when putting together clean templates. By using the 'extends' keyword, you are telling Twig that this is a child template. The other template that you are extending is the parent template.

The parent template will be used, but have it's blocks filled in with what you specify in the child template. In the example above, a title and content will be filled into index.html's 'content' block.

You can send as many blocks as you like up to the parent template. Even if the parent nests blocks, you can send them up individually.

Include

Another way to organize your templates is through the 'include' keyword.  This allows you to include another template file into your page.  Twig does this first and it is a pure swap, so it would be as if the other template already existed in place of the include tag.

{% include 'common/sidebar.html' %}

This is a great way to abstract things like sidebars.

Parent

When creating a child template that 'extends' another template, it is possible to fill in a block while using the default as well.  This is done with the 'parent' keyword.  So lets say that index.html is defined like this:

<html>
<body>
{% block content %}
<h1;>{{ this.title }}</h1;>
{% endblock content %}
</body>
</html>

We can now define a child template like this and use what has already been created as a default in 'content':

{% extends 'index.html' %}
{% block content %}
  {% parent %}
  {{ this.content }}
{% endblock content %}

Now the title will be printed because it was defined as default in the parent. After that, the content will be printed.