Fluinc
Fluinc

Reputation: 491

Twig override block inside include

I am trying to override blocks that are included.

{# index.twig #}
{% extends "default.twig" %}
{% block content %}
  html page content
{% endblock %}
{% block footer %}
  javascript
{% endblock %}

{# default.twig #}
{% include "header.twig" %}
{% block content %}
{% endblock %}
{% include "/layouts/resources/footer.twig" %}

{# footer.twig #}
{% block footer %}
{% endblock %}

I have also tried embed and that didn't work either.

{# index.twig #}
{% extends "default.twig" %}
{% block content %}
  html page content
{% endblock %}
{% block js %}
  javascript
{% endblock %}

{# default.twig #}
{% include "header.twig" %}
{% block content %}
{% endblock %}
{% embed "/layouts/resources/footer.twig" %}
  {% block footer %}
    {% block js %}
    {% endblock %}
  {% endblock %}
{% endembed %}

{# footer.twig #}
{% block footer %}
{% endblock %}

I read this could be done with 'include with' but I couldn't get that to work either.

Upvotes: 2

Views: 1871

Answers (1)

Crofly
Crofly

Reputation: 416

This works only with a trick. You have to hand over the "block" as variable.

I removed some lines of your example so thats easier to read:

index.twig

{% extends "default.twig" %}
{% block content %}
  html page content
{% endblock %}
{% block footer %}
  javascript
{% endblock %}

default.twig

{% block content %}
{% endblock %}
{% include "/layouts/resources/footer.twig" with {footer: block('footer')} %}

footer.twig

{% if footer is not empty %}
    {{ footer|raw }}
{% endif %}

Upvotes: 6

Related Questions