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.

2 Answers 2

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 %} Commented Jun 6, 2016 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. Commented Jun 6, 2016 at 11:43
  • Updated answer to be clearer about where you can/can't nest blocks with an example. Commented Jun 6, 2016 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 and acknowledge you have read our privacy policy.

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