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

Bertrand Delacretaz
  • 6,100
  • 19
  • 24

2 Answers2

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;
    }
}
John Kepler
  • 151
  • 3
  • 1
    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. – Gabriel Walt Dec 10 '14 at 11:01
  • 1
    @JohnKepler Could it be that this only works for HashMaps which don't have a String key? (e.g. `Map>` triggers `SlingException: Invalid property name` ) – NielsInc Dec 17 '15 at 15:08
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>
SWiggels
  • 2,159
  • 1
  • 21
  • 35