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

Dev Dev and nothing but the De picture Dev Dev and nothing but the De · Sep 30, 2014 · Viewed 12.5k times · Source

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

Answer

John Kepler picture John Kepler · Oct 1, 2014

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;
    }
}