【问题标题】:How to access map in velocity template file如何访问速度模板文件中的地图
【发布时间】:2014-04-10 02:51:50
【问题描述】:

当我在速度模板文件中传递Map<String,String> 时,当尝试打印 map 的值时,它会被排序(基于 ASCII 值)。

我的做法如下:

这是我的速度模板文件::

#set($tocList=${mapReference.mapValue})
#set($tocEntry="")

<div >
 #foreach($tocEntry in $tocList.keySet())
  <a href="#$tocEntry">$tocList.get($tocEntry)</a><br/>
 #end
</div>

我的 Java 代码是:

 Map<String, String> map=new HashMap<String, String>();
 Map<String,HashMap> m1=new HashMap<String, HashMap>();

   \\values that we want to print in template file

   map.put("sdfhfg", "Df lm"); 
   map.put("chdgfhd", "gBc Jk");
   map.put("dghjdhdf", "gI Ml");

   m1.put("mapValue", (HashMap) map);

  VelocityEngine velocityEngine = VelocityEngineFactory.getVelocityEngine();
  VelocityContext context = new VelocityContext();
  context.put("img",model);
  context.put("mapReference",m1);
  context.put("iterator", new IteratorTool());


  Template t = velocityEngine.getTemplate("tocTemplate.vm");
  StringWriter writer = new StringWriter();
    t.merge(context , writer);
    System.out.println(writer);

输出是:

 <div>
   <a href="#dghjdhdf">gI Ml</a><br/>
   <a href="#chdgfhd">gBc Jk</a><br/>
   <a href="#sdfhfg">Df lm</a><br/>
 </div>

为什么要对这些值进行排序?我想按原样打印地图。

【问题讨论】:

    标签: java velocity


    【解决方案1】:

    HasMap 的顺序不会随着时间的推移保持不变,从Javadoc

    这个类不保证地图的顺序;在 特别是,它不保证订单将保持不变 随着时间的推移。

    要保持顺序,您可以考虑使用LinkedHashMap,建议如下:

    这个链表定义了迭代顺序,通常是 将键插入映射的顺序

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多