2

I have 1 Matrix field: contentBlock

With 2 Block types: text photo

With nested fields: text -> text photo -> photo

My attempt at using if statements, which didn't work, to toggle between text and photo looks like the following:

{% for block in entry.contentBlock %}
    {% if block.type == 'text' %}
        {{ block.text }}
    {% endif %}
    {% elseif block.type == 'image' %}
        {% set image = block.image.first() %}
            {% if image %}
                <img src="{{ image.getUrl('thumb') }}" alt="{{ image.title }}">
            {% endif %}
{% endfor %}

Would using {% switch %} be a better method, or was I close to correct using the if statements? I think getting the hang of this will open up the true posibilities of using Craft Matrix fields.

Thank you for any input on this question.

1 Answer 1

3

Using switch is a good way to handle this, but it looks like your conditionals are just a little off:

{% for block in entry.contentBlock %}
    {% if block.type == 'text' %}
        {{ block.text }}
    {% elseif block.type == 'photo' %}
        {% set photo = block.photo.first() %}
        {% if photo %}
            <img src="{{ photo.getUrl('thumb') }}" alt="{{ photo.title }}">
        {% endif %}
    {% endif %}
{% endfor %}

The same thing with the switch syntax would be:

{% for block in entry.contentBlock %}

    {% switch block.type %}
        {% case "text" %}
            {{ block.text }}
        {% case "photo" %}
            {% set photo = block.photo.first() %}
            {% if photo %}
                <img src="{{ photo.getUrl('thumb') }}" alt="{{ photo.title }}">
            {% endif %}
    {% endswitch %}

{% endfor %}
4
  • I tried both of these methods and was not able to get the image/s to show using either; the text does show and seems to be the only part working. I tried amending the code for image.gerUrl to remove thumb, in case that that the issue, but that didn't work. Do I need to make further reference to where the image is located, or use a for entry in statement? Is these something missing which is assumed the user would have already included?
    – Craftnoob
    Commented Apr 28, 2015 at 21:31
  • Is your second block named photo rather than image? If so try case "photo" for the second switch case. If the field in that block type is also named photo and not image, you'll need to update block.image to be block.photo. Commented Apr 28, 2015 at 21:39
  • The solution was to rename image to photo in both instances you mentioned. Thank you for helping.
    – Craftnoob
    Commented Apr 28, 2015 at 22:59
  • You're welcome. I updated the code in my answer to use photo instead of image. Commented Apr 29, 2015 at 1:23

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.