3

I have a section that needs to display a certain block type (heroVideo) if a lightswitch (displayHeroVideo) within it is active. Otherwise, it should display a different block type (heroImage).

How can I write a conditional to accommodate this?

Here's what I have already which outputs both blocks if the lightswitch is active. How do I apply the conditional earlier?

{# Start hero section #}
{% for entry in entry.heroFeatured.limit(1) %}
  {% for block in entry.hero %}

  {% if block.type == "heroVideo" and block.displayHeroVideo == "1" %}

  <h1>Hero Video Markup</h1>

  {% else %}

  <h1>Hero Image Markup</h1>

  {% endif %}
{% endfor %}
{% endfor %}
6

You're close! The way you have your conditional set up now will print Hero Image Markup if either of your conditionals fail. By checking if block.displayHeroVideo is 1 on a block type that doesn't have that field, Twig will still return 0. You should only check displayHeroVideo when you know you are inside of a heroVideo block.

{% for entry in entry.heroFeatured.limit(1) %}
    {% for block in entry.hero %}

        {% if block.type == "heroVideo" %}

            {% if block.displayHeroVideo == "1" %} 

                <h1>Hero Video Markup</h1>

            {% endif %}

        {% else %}

            <h1>Hero Image Markup</h1>

        {% endif %}
    {% endfor %}
{% endfor %}
|improve this answer|||||
  • This still prints both the heroVideo block and the heroImage block if the lightswitch in heroVideo is active. I'm trying to get it so that if lightswitch is active only display the heroVideo block. – Niall Thompson Jul 22 '15 at 15:17
  • Will the heroVideo block always be the first block? – Aaron Berkowitz Jul 22 '15 at 15:21
  • Here's my matrix field setup: prntscr.com/7vsvtq – Niall Thompson Jul 22 '15 at 21:00
1

Might be better to just adjust the matrix field itself (upload a video or an image and make an if statement depending on file type).

It also is easier if you wouldnt put the image field inside the "hero" block. This way you won't have the issue regarding turning off the other block.

I would adjust your matrix to one of the mentioned methods above. If you do that you can easily access the light switch and make a if statement like:

  {% for block in entry.hero %}

        {% if block.type == "heroBlock" %}

            {% if block.displayHeroVideo %}
                <h1>Hero Video Markup</h1>
            {% else %}
                 <h1>Hero Image Markup</h1>
            {% endif %}

        {% endif %}

  {% endfor %}

This works if you merge the 2 blocks into one (named Hero Block here). It will save you alot of time writing complicated code and also keeps your code clean.

|improve this answer|||||

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.