Search code examples
javascripthtmlaem

How to loop through AEM multifield component when each field has multiple values


I've created a custom multifield component (titled "breadcrumbs") that will be used as a page's breadcrumbs nav. Each multifield item consists of a textfield and a pathbrowser. I want to list out each multifield item as an anchor tag with the "text" property as the text and the "link" property as the href.

right now, i just have my html listing out the properties as follows:

<div>
    <p>${properties.text}</p>
    <p>${properties.link}</p>
</div>

which outputs this to the page:

text 1,text 2

link 1,link 2

I know how to use data-sly-list and data-sly-repeat for each of the properties to get a list of all the texts and links like this:

<ul data-sly-list="${properties.text}">
    <li><p>${items}</p></li>
</ul>

<ul data-sly-list="${properties.link}">
    <li><p>${items}</p></li>
</ul>

but is there a way to list out both properties into one element that would look something like this:

<ul data-sly-repeat.breadcrumbs="${properties}">
    <li>
        <a href="${breadcrumbs.text}">
            ${breadcrumbs.link}
        </a>
    </li>
</ul>

I have also tried data-sly-use with a custom js file, but also can't get multiple properties to loop in one element.


Solution

  • I'd strongly recommend going with a multifield that stores the fields as JSON or nodes like ACS multifield so you get a better data structure for your purpose. I do not recommend the below solution unless you are 100% certain that both link and text are going to be the same length AND in the correct order.

    that said, assuming text and link are each multivalued properties, here is what you can do:

    <ul data-sly-list.textItem="${properties.text}">
        <li>
            <a data-sly-attribute.href="${properties.link[textItemList.index]}">
                ${textItem}
            </a>
        </li>
    </ul>
    

    this will print:

    ul>
        <li>
            <a title-href="link1">
    
            </a>
        </li>
    
        <li>
            <a title-href="link2">
    
            </a>
        </li>
    </ul>
    

    since the var name for data-sly-list, the custom identifier textItemList is created. We are interested in the member index on textItemList and use that to display the item at the same index in link by doing: properties.link[textItemList.index]

    read more about data-sly-list in the spec

    *note: you can also do this with the data-sly-repeat