0

我想使用 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());    

声明有什么问题的任何提示-> types_$fruitName.add("$fruitType.name"); 会有帮助的。

谢谢

4

1 回答 1

2

声明应该是:

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

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

于 2014-04-28T07:14:49.790 回答