1

I have an Assets field with a set of images. What is the best way to find one image that has 'featured' checkbox checked? This is the code I put together to check which of the images is marked 'featured' but I'm not sure how to modify this so to display just the 'featured' image without looping through the entire set. In my use case I need to display a page of entries with featured image for each of them.

{% for image in entry.image %}
   <a href="{{ entry.url }}"><img src="{{ image.getUrl('thumb') }}"></a>
   {% if image.featured | length %}(Featured Image){% endif %}
{% endfor %}
4
  • How are you marking the image as featured?
    – Jalen Davenport
    Aug 23, 2017 at 11:52
  • @JalenDavenport There is a 'featured' checkbox associated with each image in the 'image' assets field.
    – SoHo
    Aug 23, 2017 at 14:40
  • I can do something like this (see below) and it will display all featured images but will require looping through the entire image set for each entry.
    – SoHo
    Aug 23, 2017 at 15:26
  • For my use case I would like to check if there is a "featured" image in the set first and if not, then display the first image in the set.
    – SoHo
    Aug 23, 2017 at 15:47

1 Answer 1

1

I can do something like this and it will display all featured images but will require looping through the entire image set for each entry.

{% for image in entry.image %}
    {% if image.featured | length %}
        <a href="{{ entry.url }}"><img src="{{ image.getUrl('thumb') }}" alt="{{ image.title }}" class="img-fluid"></a>
    {% endif %}
{% endfor %}

Also came up with another solution that goes through the images until it finds a featured image and then stops. If no featured image is found it displays the first one.

{% set break = false %}
{% for image in entry.image if not break %}
    {% if image.featured | length %}
        <a href="{{ entry.url }}"><img src="{{ image.getUrl('thumb') }}" alt="{{ image.title }}" class="img-fluid"></a>                                 
      % set break = true %}
    {% endif %}
{% endfor %}

{% for image in entry.image.limit(1) if not break %}
    <a href="{{ entry.url }}"><img src="{{ image.getUrl('thumb') }}" alt="{{ image.title }}" class="img-fluid"></a>                                 
    {% set break = true %}
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.