3

I have a "single" entry which has a "entries" field. The related entries have a image field of the "Assets" type.

In the template, i want to display the image from each of the related entries. I figured i could do the following

        {% for relatedImage in entry.relatedImages %}
            {% for images in relatedImage %}
                <div><img src="{{ images.url }}" alt="{{ asset.title }}" /></div>
            {% endfor %}
        {% endfor %}

Though not only does it not work, but it is probably pretty inefficient too. Whilst I'm here, how do people go about inspecting what you get from your vars? Is there a Twig/Craft equivalent to PHP's var_dump('relatedImage')?!

Any ideas most welcome!

  • Ahh, answered my own question, oops. I had misspelled / put in the wrong tag name and i also found the dump tag. Have edited post to reflect. – John Oct 20 '14 at 10:53
  • Hey John, glad you got it worked out! You may want to separate that info and post it as an official "answer" to this question. That would make it much easier for future readers to follow your whole process. – Lindsey D Oct 20 '14 at 16:41
  • That's exactly how I do it in my templates too, looks good to me! – darylknight Oct 28 '14 at 18:57
2

Got a solution that is cleaner than nested for loops.

{% set myRelatedImage = entry.relatedImages.first %}

then I can do

<img src='{{ myRelatedImage.images.first.url }}'>

My use case was slightly different. I have a bunch of sermons entries that are related to a series entry. It's the series entry that has the image attached.

This worked very nicely.

| improve this answer | |
2

I am an idiot, i just misspelled things. I'm still interested to know a more efficient way to do this though?

Corrected code:

            {% for relatedImage in entry.relatedImages %}
                {% for images in relatedImage.image %}
                    <div><a href="{{ relatedImage.url }}"><img src="{{ images.url }}" alt="{{ relatedImage.title }}" /></a></div>
                {% endfor %}
            {% endfor %}

And the debug would be {{ dump(relatedImage) }}

| improve this answer | |
  • I thought there'd be a more succinct way of doing this as well – Steven Grant Feb 25 '16 at 10:24
0

You could use Craft's relations API and try something like this:

{% set assets = craft.assets.relatedTo(entry.relatedEntries) %}

However, one thing I have noticed with this approach is that it does not return duplicate images. For example, lets say you have two related entries in your single's entries field, and each of those entries have the same image, it will only return the image once. This could be either positive or negative depending on what you want to do with the data.

| 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.