在 Velocity 模板中按名称引用地图
很确定这个问题有一个简单的答案,但就是找不到正确的 VTL 语法。
在我的上下文中,我传递了一个包含其他地图的地图。我想按名称引用这些内部映射并在我的模板中分配它们。内部映射由应用程序的不同部分构建,然后
通过示例
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添加到上下文中
#set ($in_map = $msgData.get($inner_map) )
data:
$in_map.data_1
$in_map.a_date
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
by way of example
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() );
}
Template - test.vm
#set ($in_map = $msgData.get($inner_map) )
data:
$in_map.data_1
$in_map.a_date
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
或
Try
or
给出的答案对我不起作用,但确实让我以不同的方式思考这个问题。我通过创建一个方法解决了这个问题,该方法可以基于字符串查找数据的子部分并返回地图列表。
如果您的基础数据是 XML 文档,这甚至可以工作,因为您可以传入 xPath 并让该方法返回 tagName tagValues 的映射。这提供了很大的灵活性。
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.
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.