1

This is my _layouts/main.twig:

<body {% if bodyId is defined %}id="{{ bodyId }}"{% endif %}>

  {% include '_layouts/header.twig' %}

  {% block main %}

  {% endblock %}

</body>

Then i have blog/_entry.twig with:

{% extends '_layouts/main' %}

{% block main %}

{% switch entry.entryType.entryIs.value %}
    {% case 'listing' %}
        {% include 'blog/_listing.twig' %}
    {% case 'listingSimple' %}
        {% include 'blog/_listing-simple.twig' %}
    {% case 'article' %}
        {% include 'blog/_single-entry.twig' %}
{% endswitch %}

{% endblock %}

If I do:

{% set bodyId = 'article' %}

in my blog/_single-entry.twig that does not work.

But it works if i set bodyId in my index.twig in the root that is not a include.

2 Answers 2

2

So, I had a similar problem... Had a few things that didn't work for me, but I got it to work. First item: putting the set bodyID inside the {% block main %} didn't work for me, it had to be outside of that. Second: it didn't like being a the switch/case format, so I did it as an if-check.

So, try something like this:

{% extends '_layouts/main' %}

{% if entry.entryType.entryIs.value == "listing" %}
    {% set bodyId = 'listing' %}
{% elseif entry.entryType.entryIs.value == "listingSimple" %}
    {% set bodyId = 'listing-simple' %}
{% elseif entry.entryType.entryIs.value == "article" %}
    {% set bodyId = 'single-entry' %}
{% endif %}

{% block main %}

{% switch entry.entryType.entryIs.value %}
    {% case 'listing' %}
        {% include 'blog/_listing' %}
    {% case 'listingSimple' %}
        {% include 'blog/_listing-simple' %}
    {% case 'article' %}
        {% include 'blog/_single-entry' %}
{% endswitch %}

{% endblock %}
1
  • thanks that works. I could swear i tried that :-( Commented Aug 26, 2019 at 22:46
2

So Twig has a particular processing order for things like variables, includes, extends and all that sort of stuff. Basically, you can't set a variable in an included template and then use that in an extended template.

Here's a great article that goes into this topic in a little more depth: https://nystudio107.com/blog/twig-processing-order-and-scope - I'd highly recommend you give it a read.

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.