Ad

How Can I Display The Image From The Related Entry For Each Entry In Craft CMS And Twig?

- 1 answer

I have a a list of entries. Each entry has a related person. Each related person has an avatar.

On my index page I am looping over the entries and creating a <div> with the persons details. Eg

{% set person = entry.relatedPerson[0] ?? null %}

<p>{{person.firstName}} {{person.lastName}} </p>

I need to access the picture related to the person.

Have tried this which displays a list of every asset that is an image in its own div.

{% set person = entry.relatedPerson[0] ?? null %} 
{% for image in craft.assets.kind('image') %}
    <li>
          <img src="{{ image.getUrl }}" alt="{{ image.title }}">
    </li>
{% endfor %}

I have also tried this which shows nothing

{% set person = entry.relatedPerson[0] ?? null %}
{% for image in person.assets.kind('image') %}
    <li>
        <img src="{{ image.getUrl }}" alt="{{ image.title }}">
    </li>
{% endfor %}

How can I add the relatedPerson image to each card? Also it would be great if you could explain as I'm not understanding templating. The docs aren't sufficient for me

Ad

Answer

I think you missed the parenthesis after getUrl "()" in your code to fetch the image. The getUrl is a method.

{% set person = entry.relatedPerson[0] ?? null %} 
{% for image in craft.assets.kind('image') %}
    <li>
          <img src="{{ image.getUrl() }}" alt="{{ image.title }}">
    </li>
{% endfor %}

Use the getUrl as I used in the above code. I hope it will work for you.

Thanks.

Ad
source: stackoverflow.com
Ad