Iteration (for loop) in sightly

2019-05-08 11:33发布

问题:

I had used <c:forEach> in jstl. Now i want to use sightly.

My usecase is to print numbers from 1 to 10 then how can i iterate in sightly as for loop in java

回答1:

Sightly doesn't let you put any logic in it by design. What you should do is, you should customize your underlying model so that you can retrieve a prepared list of irrelevant (from Sightly's perspective) length that contains data that needs to be displayed. After that, just use data-sly-list. You'll need to google for more details, but in general, this is how you use lists in Sightly:

<ul data-sly-list.myitem="${mymodel.myitems}" data-sly-unwrap>
  <li>${myitem.foo}</li>
</ul>

EDIT: As pointed out by @nateyolles, you can iterate over a specific range of items by using the index in a test condition (<li data-sly-test="${itemList.count >= 2 && itemList.count <= 6}">${item}</li>), though I am not sure if this is the "Sightly way". Personally, I would advise not to, unless it would make your life noticeably easier.



回答2:

Please have a lok at this AEM Forums poat:- http://help-forums.adobe.com/content/adobeforums/en/experience-manager-forum/adobe-experience-manager.topic.html/forum__wtot-hi_i_need_toite.html

Loop with fixed number of items

<ul data-sly-list="${ [1,2,3,4] }">
<li>${item}</li>
</ul>

Also please have a look at the documentation:-

Link:- https://docs.adobe.com/docs/en/aem/6-1/develop/sightly/block-statements.html

//

LIST

data-sly-list: Repeats the content of the host element for each enumerable property in the provided object.

Here is a simple loop:

<dl data-sly-list="${currentPage.listChildren}">
    <dt>index: ${itemList.index}</dt>
    <dd>value: ${item.title}</dd>
</dl>

Code samples are intended for illustration purposes only.

The following default variables are available within the scope of the list:

item: The current item in the iteration.

itemList: Object holding the following properties:

index: zero-based counter (0..length-1).

count: one-based counter (1..length).

first: true if the current item is the first item.

middle: true if the current item is neither the first nor the last item.

last: true if the current item is the last item.

odd: true if index is odd.

even: true if index is even.

//

<ul data-sly-list.child="${currentPage.listChildren}">
  <li class="${ childList.odd ? 'odd' : 'even'}">${child.title}</li>
</ul>

//

<div data-sly-list.children="${resource.listChildren}">
    <div data-sly-list.fields="${children.listChildren}">
        <div data-sly-test=${fieldsList.last}> DO SOMETHING BEFORE LAST NODE</div>
        <div data-sly-resource="${fields.path}"></div>
    </div>
</div>

So according to your use-case you can use :

<ul data-sly-list.child="${currentPage.listChildren}">
   <li data-sly-test="${childList.index <= 5}">${child.title}</li>
</ul>

I hope this will work for you.

Thanks and Regards

Kautuk Sahni