Hi
Wish you a wonderful new year.
HOW TO ITERATE MAP IN HTL(formerly know as sightly)
Suppose you have a Map constructed in your sling model which you want to iterate in HTL, then you can do so using below
Code in Sling Model for constructing map
private Map<Integer,String> map;
public Map<Integer,String> getMap() {
return map;
}
@PostConstruct
public void constructMap() {
map = new HashMap<Integer, String>();
map.put(1,"A");
map.put(2,"B")
}
Code in HTLfor iterating the HashMap
<sly data-sly-use.model="org.training.ListingModel">
<ul data-sly-list.key="${model.map}">
<li> KEY: ${key}, VALUE: ${model.map[key]}</li>
</ul>
</sly>
Output :-
A
B
Iterate Map of List in HTL:-
Sometimes due to HTML constraint we have to iterate over a map of list.
For Example, suppose you have a component which displays a list of products. The products should be displayed in row wise. But the no of products in each row would be varied depending on the total no of products. This can be controlled using JavaScript as well but still you want to implement the logic in Java then you cab create a Map of List.
Code in Sling Model for constructing map
private Map<Integer,List<ProductModel>> map;
private List<ProductModel> products;
public Map<Integer,String> getMap() {
return map;
}
@PostConstruct
public void constructMap() {
map = new HashMap<Integer, List<ProductModel>>();
products = Lists.newArrayList();
products.add(ele1);
products.add(ele2);
map.put(1,products);
}
Code in HTL for iterating the List of HashMap :-
<sly data-sly-use.model="org.training.ListingModel">
<ul data-sly-list.keyName="${model.map}">
<ul data-sly-list.key="${model.map[keyName]}">
<li> ${key.productTitle}</li>
</ul>
</ul>
</sly>
Output
1
ele1
elem2
Source Article :- https://cqbasics.blogspot.in/2016/06/iterate-map-and-list-in-sightly-map-of.html
Reference Posts:
Link:- http://stackoverflow.com/a/26148614/6433590
Link:- http://www.wemblog.com/2016/02/how-to-sightly-in-aem-cq.html
I hope this would help you.
~kautuk