Kenny
Kenny

Reputation: 2144

Twig Block content into Include

I'm trying to put {% block body %} into an {% include 'bundle::...' %}. Here's my code below:

{% extends '::base.html.twig' %}

{% block title %}{{ id }}{% endblock %}

{% block content %}

    {% include 'scraperBundle::Event/sideLeft.html.twig' %}
    {% include 'scraperBundle::Event/sideRight.html.twig' %}

{% endblock %}

{% block body %}
    stuff here to go ingo block body
{% endblock %}

The problem is everything loads correctly except my {% block body %} does not go into the place it should, which is in the {% include 'scraperBundle::Event/sideLeft.html.twig' %} file here:

<div class="event-info">
    {% block body %}{% endblock %}
</div>

I'm not well versed in Twig, anyone know the correct method or how to do this?

Thanks.

============== EDIT ==============

Can I have nested {% block nameof %}?

{% extends '::base.html.twig' %}

{% block title %}{{ id }}{% endblock %}

{% block content %}

    {% embed 'scraperBundle::Event/sideLeft.html.twig' %}

        {% block body %}
        {% endblock %}

    {% endembed %}

    {% embed 'scraperBundle::Event/sideRight.html.twig' %}

{% endblock %}

============== EDIT 2 (Working) ==============

Added second {% endembed %} and now it works. I guess you can, indeed, have nested {% block %} stuff.

Can I have nested {% block nameof %}?

{% extends '::base.html.twig' %}

{% block title %}{{ id }}{% endblock %}

{% block content %}

    {% embed 'scraperBundle::Event/sideLeft.html.twig' %}

        {% block body %}
        {% endblock %}

    {% endembed %}

    {% embed 'scraperBundle::Event/sideRight.html.twig' %}
    {% endembed %}

{% endblock %}

Upvotes: 0

Views: 1283

Answers (2)

jbafford
jbafford

Reputation: 5668

You can't specify or override blocks from an included template. Please see this answer to a similar question for some background information as to why that doesn't work.

{% embed %} will do what you need, though.

For your second question: blocks can be nested. Nested blocks are quite common, in practice.

Upvotes: 1

Igor Pantović
Igor Pantović

Reputation: 9246

You cannot override block from included template. What you're looking for is embed:

# template1.html.twig

{% embed "template2.html.twig" %}
    {% block override_me %}
        This will override "HAI" text
    {% endblock %}
{% endembed %}

# template2.html.twig

Something here
{% block override_me %}HAI{% endblock %}

Upvotes: 1

Related Questions