如何使用变量声明访问速度模板文件中的地图

时间:2016-05-14 06:18:38

标签: java templates velocity

我创建的地图包含最终传递到homeAddress地图的邮政地址。参见下面的代码

        Map map1 = new HashMap();
        map1.put("address", "address1 trinity");
        map1.put("address2", "addressmg road");
        map1.put("city", "bangalore");
        map1.put("state", "karnataka");

        Map map2 = new HashMap();
        map2.put("postal_address",map1);

        VelocityContext context = new VelocityContext();
        context.put("homeAddress",map2);

模板代码:

    Variable Declaration:
    #set ($PostalAddress_Address2 ="address2")
    #set ($PostalAddress_City ="city")
    #set ($PostalAddress_State ="state")
    Iterating the Map:
    #set($tocList=${homeAddress.postal_address})
    $tocList.get($PostalAddress_Address2)
    $tocList.get($PostalAddress_State)
    $tocList.get($PostalAddress_City)

上面的代码工作正常。但是当我将postal_address_main的变量声明替换为postal_address时,它就无法正常工作

   #set ($postal_address_main ="postal_address")
    #set($tocList=${homeAddress.postal_address_main })

对此有何建议?如何从map中获取值时替换Variable声明?

1 个答案:

答案 0 :(得分:0)

修正了上述问题,

 #set ($postal_address_main ="postal_address")
 #set($tocList=$homeAddress.get($postal_address_main))

首先获取地图($homeAddress),然后通过替换VLT($postal_address_main)从地图中获取实际值。