how do I get key/value in sightly from java use class hashmap
Asked Answered
H

2

8

I have a basic java use class object that extends WCMUSE and a simple hashmap method - in the sightly code - I have something like

${item}

${item.key}

${item.value}

does not work - how do I return key/value pair in sightly code

Health answered 30/9, 2014 at 15:10 Comment(0)
E
13

There is an example at Sightly Intro Part 3 and the use of ${item} and ${itemList} as a variables is documented on the AEM Docs Sightly Page. This page also gives the following example for accessing dynamic values:

<dl data-sly-list.child="${myObj}">
<dt>key: ${child}</dt>
<dd>value: ${myObj[child]}</dd>
</dl>

Here is an example with a simple HashMap.

HTML with Sightly:

<div data-sly-use.myClass="com.test.WcmUseSample" data-sly-unwrap>
    <ul data-sly-list.keyName="${myClass.getMyHashMap}">
        <li>KEY: ${keyName}, VALUE: ${myClass.getMyHashMap[keyName]}</li>
    </ul>
</div>

Java:

package com.test;

import java.util.HashMap;
import java.util.Map;
import com.adobe.cq.sightly.WCMUse;

public class WcmUseSample extends WCMUse {
private Map<String, String> myHashMap;

    public void activate() throws Exception {
        myHashMap = new HashMap<String, String>();
        for (int i = 0; i < 10; ++i) { 
            myHashMap.put(""+i, "Hello "+i);
        }
    }
    public Map<String,String> getMyHashMap() {
        return myHashMap;
    }
}
Enchant answered 1/10, 2014 at 18:59 Comment(2)
The surrounding div with data-sly-use.myClass is not necessary. It should be avoided as much as possible to create elements that are removed again with data-sly-unwrap to keep the template markup as close as possible from the generated markup. The data-sly-use.myClass should thus be placed on the UL element instead.Kkt
@JohnKepler Could it be that this only works for HashMaps which don't have a String key? (e.g. Map<Tag, List<Tag>> triggers SlingException: Invalid property name )Attorneyatlaw
H
0

You can also try the following (AEM 6.4) :

Note the data-sly-test.hashMap for emptycheck.

<div data-sly-use.pageController="com.corp.wcms.core.pages.anypage.PageController"

  <div data-sly-test.hashMap="${pageController.myHashMap}" data-sly-unwrap>
     <ul data-sly-list.keyName="${hashMap}">
       <li>KEY: ${keyName}, VALUE: ${hashMap[keyName]}</li>
     </ul>
  </div>

</div>
Headrace answered 3/12, 2018 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.