Skip to content

Can I add html component every two elements of a list from Java model using Sighlty?

I need to iterate every two elements of a list from model Java using Slightly. So I can add html components every two elements.

Can you help me, please?

Answer

According to the HTL specification:

An additional itemList (respectively <variable>List in case a custom identifier/variable was defined using data-sly-list.) identifier is also available within the scope, with the following members:

  • index: zero-based counter (0..length-1);
  • count: one-based counter (1..length);
  • first: true for the first element being iterated;
  • middle: true if element being iterated is neither the first nor the > * last;
  • last: true for the last element being iterated;
  • odd: true if count is odd;
  • even: true if count is even.

So, in your case, where the custom identifier is listIcon, you would need to test listIconList.even instead of boxSPID.listIcon.even.

For your snippet, if you want to insert a row for each even element:

<sly data-sly-test="${boxSPID.listIcon}"
     data-sly-list.listIcon="${boxSPID.listIcon}">
    ${listIconList.count} <!-- You can remove this line, it's just for debug -->
    <div class="row" data-sly-test="${listIconList.even}">
        <div class="${listIcon.iconValue}">
            ${listIcon.label}
        </div>
    </div>
</sly>

If you want to group together two consecutive elements into the same row, you could add the group start/end tags conditionally:

<sly data-sly-test="${boxSPID.listIcon}"
     data-sly-list.listIcon="${boxSPID.listIcon}">
    <sly data-sly-test="${listIconList.odd}"><div class="row"></sly>
        <div class="${listIcon.iconValue}">
            ${listIcon.label}
        </div>
    <sly data-sly-test="${istIconList.even || listIconList.last}"></div></sly>
</sly>

or skip one set of elements (even) and reference them by index to include them with the output (odd):

<sly data-sly-test="${boxSPID.listIcon}"
     data-sly-list.listIcon="${boxSPID.listIcon}">
    <div class="row" data-sly-test="${listIconList.odd}">
        <div class="${listIcon.iconValue}">
            ${listIcon.label}
        </div>
        <div class="${${boxSPID.listIcon[listIconList.count].iconValue}}" data-sly-test="${boxSPID.listIcon[listIconList.count]}">
            ${boxSPID.listIcon[listIconList.count].label}
        </div>
    </div>
</sly>