How to Iterate Map in Sightly
Suppose you have a Map constructed in your sling model which you want to iterate in Sightly, 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 Sightly for 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 Sightly:-
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 Sightly 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
Awesome bro :)
ReplyDeleteHi Mahesh,
ReplyDeleteI am facing issue while iterating hashmap and Person class contains address property which is of again type HashMap. I am not able to get object of class Address. Any suggestions ?
Hi, Could you please explain in detail what's the error ?
Delete