5

I'm not sure if it is appropriate to post twig questions on this forum? I have a question about nested blocks and using the twig "parent" function. I'm running into unexpected behaviour on a craft site i'm building.

My parent and child template layouts.

{# Parent Template #}
{% block breadcrumbs %}
    {% block crumb %}

    {% endblock %}
{% endblock %}

{# Child Template #}
{% block breadcrumbs %}
    {{ parent() }}
    {% block crumb %}
        My custom content
    {% endblock %}
{% endblock %}

What I'm trying to achieve

  • On my child template, I'm trying to retain the content in block breadcrumbs but override the content in block crumb.
  • However when I use the parent function in my child template, it does not respect "my custom content" and uses the block crumb content defined in the parent template.
2
  • Who you ever add content after the crumb block? – Luke Holder Aug 17 '14 at 3:01
  • Tested your code, Matt. I do get the parent's "breadcrumbs" content with the parent() function and I also get the child's "crumb" content with this. Problematic though, you'll get "My custom content" twice if you're nesting the blocks in the child layout. But that is as expected, if you think about it. – carlcs Aug 18 '14 at 10:35
7

Try to keep the blocks separate in your child template. That's how it's done in a comparable example in the Twig Documentation.

Parent Template:

{% block breadcrumbs %}
    {% block crumb %} 
    {% endblock %}
{% endblock %}

Child Template:

{% extends "parent.html" %}

{% block breadcrumbs %}
    {{ parent() }}
{% endblock %}

{% block crumb %}
    My custom content
{% endblock %}

.

Edit:

If you're not adding any content to your "breadcrumbs" block from the child template, you can also omit that block completely:

{% extends "parent.html" %}

{% block crumb %}
    My custom content
{% endblock %}
2
  • Hey @carlcs that does not work for me either. It is still hitting the parent block crumb content – Matt Aug 17 '14 at 1:09
  • Hey @carlcs you are right. This does work as you've suggested. However, I can only get it to work with other blocks. There seems to be some error with my crumb block which is not working for me. Thanks for your help. – Matt Aug 19 '14 at 13:16

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.