twigoctobercmscraftcms

How can I display the image from the related entry for each entry in craft CMS and twig?


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


Solution

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