2

I'm new to Craft and using Matrix fields.

I've got a matrix field called imageDouble with two child fields called firstImage and secondImage.

The template code I have is returning a 500 error. I want it to display firstImage and secondImage each in their own separate div. Any help with my structure here?

{% for block in entry.body %}

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

        <div class="row text detail">

            <div class="col-xs-12 col-md-6 col-md-offset-3">

                <p>{{ block.textContent }}</p>

            </div>

        </div>

    {% elseif block.type == "imageDouble" %}

        {% set image = block.image.first() %}

            {% if image %}

            <div class="row imageDouble detail">

                <div class="col-xs-12 col-md-6">

                    <img src="{{ firstImage.getUrl() }}">

                </div>

            {% endif %}

        {% set image = block.image.first() %}

            {% if image %}

                <div class="col-xs-12 col-md-6">

                    <img src="{{ secondImage.getUrl() }}">

                </div>

            </div>

            {% endif %}
 {% endfor %}
7

I think the issue here where you are setting your image variable.

{% set image = block.image.first() %}

This should reference the field handle of the asset you are trying to get the url of, so it should be this instead:

{% set image = block.firstImage.first() %}

Then where you try and display the image it should be:

<img src="{{ image.getUrl() }}">

You would then need to update this for the secondImage.

It might be worth mentioning that there is a cleaner way to achieve what you’re after, with just one asset field.

You can upload multiple images to a single asset field, so assuming firstImage has two assets attached, your code could be shortened to the following:

...
{% elseif block.type == "imageDouble" %}

 {# this has two assets attached #}
 {% set images = block.firstImage %}

 {% if images and images|length %}

  <div class="row imageDouble detail">

    {# Loop through the images #}
    {% for image in images %}

      <div class="col-xs-12 col-md-6">
        <img src="{{ image.getUrl() }}">
      </div>

    {% endfor %}

  </div>

 {% endif %}

{% endif %}
...

This will help keep your code from repetition and will be easier to maintain in the future :)

  • Thanks a million for not only solving my problem but proposing an even cleaner solution! – Jeremy P. Beasley Dec 28 '14 at 19:11
  • Not a problem :) glad it helped you out! – Alec Ritson Dec 29 '14 at 12:37

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.