在 Velocity 模板中按名称引用地图 [英] Reference a Map by name within Velocity Template

查看:23
本文介绍了在 Velocity 模板中按名称引用地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很确定对此有一个简单的答案,但就是找不到正确的 VTL 语法.

Pretty sure there is an easy answer to this, but just can't find the right VTL syntax.

在我的上下文中,我传递了一个包含其他地图的地图.我想通过名称引用这些内部映射并在我的模板中分配它们.内部地图由应用程序的不同部分构建,然后添加到上下文中

In my context I'm passing a Map which contains other Maps. I'd like to reference these inner maps by name and assign them within my template. The inner maps are constructed by different parts of the app, and then added to the context

举个例子

public static void main( String[] args )
    throws Exception
{

    VelocityEngine ve = new VelocityEngine();
    ve.init();
    Template t = ve.getTemplate( "test.vm" );
    VelocityContext context = new VelocityContext();

    Map<String,Map<String,String>> messageData = new HashMap<String, Map<String,String>>();


    Map<String,String> data_map = new HashMap<String,String>();
    data_map.put("data_1","1234");
    data_map.put("a_date", "31-Dec-2009");

    messageData.put("inner_map", data_map);

    context.put("msgData", messageData);
    StringWriter writer = new StringWriter();

    t.merge( context, writer );
    System.out.println( writer.toString() );
}

模板 - test.vm

Template - test.vm

#set ($in_map =  $msgData.get($inner_map) )

data:

    $in_map.data_1
    $in_map.a_date  

推荐答案

给出的答案对我不起作用,但确实让我以不同的方式思考问题.我通过创建一个方法来解决这个问题,该方法可以根据字符串查找数据的子部分并返回地图列表.

The answer given didn't work for me but did get me thinking about the problem in a different way. I Resolved this by creating a method which can lookup subsections of data based on a string and returns a list of maps.

#set( $data = $confirmData.getCollection("MSG_DATA").get(0) )

如果您的基础数据是 XML 文档,这甚至可以工作,因为您可以传入 xPath 并让该方法返回 tagName tagValues 的映射.这提供了很大的灵活性.

This even works if your underlying data is an XML document, as you can pass in an xPath and have the method return a map of the tagName tagValues. This provides a lot of flexibility.

#set( $data = $confirmData.getCollection("//Message/header[sendFrom='xxx']").get(0) )

这篇关于在 Velocity 模板中按名称引用地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆