使用Map的嵌套foreach在Velocity中无法正常工作

时间:2014-04-25 06:37:11

标签: velocity vtl

我想使用Velocity生成以下代码段。


    Map<String, List<String>> fruitsAndTypesMap = new HashMap<String, List<String>>();
    String fruit_Apple = "Apple";
    List<String> types_Apple = new ArrayList<String>();
        types_Apple.add("KA");
        types_Apple.add("WA");
    fruitsAndTypesMap.put(fruit_Apple, types_Apple);    

    String fruit_Orange = "Orange"; 
    List<String> types_Orange = new ArrayList<String>();
        types_Orange.add("HO");
        types_Orange.add("LO");
    fruitsAndTypesMap.put(fruit_Orange, types_Orange);

我的template_fruits.vm文件如下。


#if ($fruitsMap.size()>0)
    Map<String, List<String>> fruitsAndTypesMap = new HashMap<String,List<String>>();
    #foreach( $fruitName in $fruitsMap.keySet() )
        String fruit_$fruitName = "$fruitName";
        List<String> types_$fruitName = new ArrayList<String>();
            #foreach( $fruitType in $fruitsMap.get($fruitName) )
                     types_$fruitName.add("$fruitType.name");
            #end
        fruitsAndTypesMap.put(fruit_$fruitName, types_$fruitName);
    #end
#end    

问题在于:types_ $ fruitName.add(“$ fruitType.name”); 它没有正确评估$ fruitName。 但是,如果我将语句修改为:types _($ fruitName).add(“$ fruitType.name”);,它被正确评估,但值被括号括起来。我不明白评估的括号技巧。

下面的代码可以用来加载$ fruitsMap


      public static Map<String, List<Fruit>> getFruitsMap(){

    Map<String, List<Fruit>> fruitsMap = new HashMap<String, List<Fruit>>();
    List<Fruit> applesList = new ArrayList<Fruit>();
    Fruit fruit_Apple = null; 
        fruit_Apple = new Fruit();  fruit_Apple.setName("KA"); 
    applesList.add(fruit_Apple);
        fruit_Apple = new Fruit();  fruit_Apple.setName("WA");
    applesList.add(fruit_Apple);

    List<Fruit> orangesList = new ArrayList<Fruit>();
    Fruit fuit_Orange = null;
        fuit_Orange = new Fruit();  fuit_Orange.setName("HO");
    orangesList.add(fuit_Orange);
        fuit_Orange = new Fruit();  fuit_Orange.setName("LO");
    orangesList.add(fuit_Orange);

    fruitsMap.put("Apple", applesList);
    fruitsMap.put("Orange", orangesList);
    return fruitsMap;
}

与模板执行相关的代码:


VelocityEngine velEngine = new VelocityEngine();
        velEngine.init();
    Template template = velEngine.getTemplate("template_fruits.vm");
    VelocityContext context = new VelocityContext();
        context.put("fruitsMap", FruitClient.getFruitsMap());
    StringWriter writer = new StringWriter();
        template.merge(context, writer);
    System.out.println("Content: " + writer.toString());    

任何有关陈述错误的提示 - &gt; types_ $ fruitName.add( “$ fruitType.name”);会有所帮助。

由于

1 个答案:

答案 0 :(得分:2)

陈述应该是:

types_${fruitName}.add("$fruitType.name");

否则,Velocity会尝试在$ fruitName对象上调用add方法。