Can I fliter out a Twig block from one page to another?

261 Views Asked by At

Hope someone can please advise. I'm working on a theme for a CMS. I have one twig-based page as the theme template, so obviously all of the Twig blocks for the different types of pages are in the one document. The CMS has two types of pages that can be created and viewed via the page builder. At the moment, all of the Twig blocks appear in page A as well as page B from the font-end. Is it possible for me to write some Twig code that will enable to me to display a Twig block on page A, but not on page B? I understand I need some sort of filter, but do I filter by url, or is there a better way? Appreciate any help you can give me.

1

There are 1 best solutions below

1
DarkBee On

To prevent a block from an extended template from showing you can override the block

main.twig

{% block foo %}
    Foo
{% endblock %}

{% block bar %}
    Bar
{% endblock %}

child.twig

{% extends "main.twig" %}
{% block foo %}{% endblock %}

The snippet above will just display Bar

To take it a step further, you can override a block and still let the original block of the extended template be executed, by using the function {{ parent() }}

child.twig

{% extends "main.twig" %}
{% block foo %}
    Lorem Ipsum<br />
    {{ parent() }}
{% endblock %}

This will output

Lorem Ipsum<br />
Foo
Bar

With this explained, you can wrap the function call parent() in any condition you like, thus controlling which block to show/hide

{% extends "main.twig" %}
{% block foo %}
    {% if conditionA == true %}
        {{ parent() }}
    {% endif %}
{% endblock %}

{% block bar %}
    {% if conditionB == true %}
        {{ parent() }}
    {% endif %}
{% endblock %}

demo