1

Problem: I am working on Liferay 6.0.5. I want to read a java map from request and iterate over it in a velocity template. The velocity is not able to read it as map rather it is taken as String value.

JSP Code: 1. Reading categories:

List<AssetCategory> curCategories = assetEntry.getCategories();
Map<String, String> catgrMap=new HashMap<String, String>();
String temp="";
String key=null;
for (AssetCategory category : curCategories) {
    key=(AssetVocabularyServiceUtil.getVocabulary(category.getVocabularyId())).getName();
    if(!temp.equalsIgnoreCase(key)){
       catgrMap.put(key,category.getName());
       temp=key;
    }else{
       String val=(String)catgrMap.get(key);
       val=val+","+category.getName();
       catgrMap.put(key,val);
       temp=key;
    }   
}
  1. Setting Map in request

    request.setAttribute("categoryMap",catgrMap);
    

What I want: I want to iterate over this catgrMap and read its keys and values. Here is the steps:

  1. Get map from request :

    #set ($categoryMap= $request.get('attributes').get('categoryMap'))
    
  2. Iterate over map - There are many ways to iterate over a map in velocity and here are some of them. 2.1

    #foreach ($mapEntry in $categoryMap.entrySet())
    <tr>
      <td>$mapEntry.key</td>
        <td>$mapEntry.value</td>
    

    #end

    2.2
    
    #set( $keys = $categoryMap.keySet() )
    

    #foreach( $key in $keys ) $key $categoryMap[$key] #end

    2.3
    #set ($map = $categoryMap.getMap() )
    
    #foreach ($mapEntry in $map.entrySet())
    

    $mapEntry.key $mapEntry.value #end

  3. The Roadblock: The problem is not how we are iterating, its how the velocity reads the map from request. It reads the map as String object so iteration is not possible. The ${categoryMap.class.name} returns String and not Map.

What are the possible ways to pass a map to velocity and iterate over it? We are not keen on using ext-plugin.

peterh
  • 11,875
  • 18
  • 85
  • 108
Sheetal Mohan Sharma
  • 2,908
  • 1
  • 23
  • 24
  • Why not pass the map through template context, as it is meant to be? – serg Jun 21 '11 at 15:36
  • Is this is Liferay 6, which I'm assuming it as you mention ext-plugin, why not use the Plugins-SDK rather than do this in Velocity? – Jonny Jun 23 '11 at 07:57
  • One question, where is this velocity located? Theme or Web Content Template? I've run into this issue as well and as far as I can remember, I believe what the $request is not the actual request object but actually just a Map. – rp. Jun 24 '11 at 19:04
  • @RP - You are right, this is in web-content template. Can you guys post some code with reference to my post above? Though I have made it working using some workaround and playing with String classes but I will be happy to know right way from you guys. – Sheetal Mohan Sharma Jul 14 '11 at 11:24

0 Answers0