1

I have a videoPost block in a Matrix field. Each videoPost has a imageField. I am trying to display the block’s image if imageField is defined. This is returning images for each block that has imageField defined when I only want to return the specific block’s image.

{% for block in entry.matrixField.type('videoPost') %}
    {% if block.imageField | length %}
        {% for asset in block.imageField %}
            <img src="{{asset.getUrl}}" alt="{{ asset.title }}" />
        {% endfor %}
    {% endif %}
{% endfor %}
1

Try replacing

{% for asset in block.imageField %}
    <img src="{{asset.getUrl}}" alt="{{ asset.title }}" />
{% endfor %}

with

{% set asset = block.imageField.first() %}
<img src="{{asset.getUrl}}" alt="{{ asset.title }}" />

If you're using Craft 3, replace .first() with .one()

|improve this answer|||||
  • This makes sense and I thought for sure this would solve it but this still returns images for each block. – seth Oct 26 '18 at 13:58
  • Are you sure it isn't an issue with your initial for loop? If I test your code as-is, the loop isn't limited to a single block, it's calling all of your videoPost blocks, so it's displaying all of the images associated with those blocks. – artmem Oct 26 '18 at 14:36
  • Yes, that is the case. Thank you. I removed the initial for loop and used the following {% if block.imageField | length %}{% set asset = block.imageField.first() %}<img src="{{ siteUrl | trim('/') }}{{asset.getUrl}}" alt="{{ asset.title }}" />{% endif %} – seth Oct 26 '18 at 15:08

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.