3

I'm using twigfiddle.com for now because i want to simulate Twig templates before moving on using Craft.

Base.twig (main template)

{% block head %}
    {% block content %}{% endblock %}
{% endblock %}

Child.twig

{% extends "Base.twig" %}

{% block content %}
    Content from child.twig
{% endblock %}

I expect an output of "Content from child.twig" but instead get nothing.

4

You aren't able to nest blocks in the template where that block is output - all content inside a block in the parent template is replaced by the child templates content, hence why you don't see your content block being output inside your head block. Likewise you can't use multiple extends within one template.

You can however nest blocks in a child template and output them in your extended template.

Base.twig (main template)

// Will display "content" and "sidebar content"
{% block content %}{% endblock %}

// Will only display "sidebar content"
{% block sidebar %}{% endblock %}

Child.twig

{% extends "Base.twig" %}

{% block content %}
  Content
  {% block sidebar %}
    Sidebar content
  {% endblock %}
{% endblock %}

More info on the topic can be found in Twigs documentation.

3
  • If i can't nest blocks, then why the twig doc you linked has this code: {% block sidebar %} {% block inner_sidebar %} ... {% endblock inner_sidebar %} {% endblock sidebar %} Jun 6 '16 at 11:36
  • I could somehow get how the extends, parent-child relationship and blocks work just a little, i see that as a starting point for learning. Thanks for answering. Jun 6 '16 at 11:43
  • Updated answer to be clearer about where you can/can't nest blocks with an example. Jun 6 '16 at 12:00
1

The code block you have outlined above calls for a third template. Take a look at this fiddle to see how the nesting would work.

http://twigfiddle.com/ul64wd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.