速度模板引擎 - 键值映射 [英] Velocity Template engine - key-value-map

查看:37
本文介绍了速度模板引擎 - 键值映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用键值映射到 Velocity 时遇到了一些问题.

I have some problems wo use a key-value-map into Velocity.

有人有这个功能的例子吗?

Someone has an example of this functionality?

$myMap ={}

$myMap.put("mykey1", "myvalue")
$myMap.delete("mykey1")
$myMap.getValue("mykey1")

推荐答案

正如 Nathan 所说,你应该使用:

As Nathan said, you should use:

#set ($myMap = {})

创建一个新地图并将其分配给一个变量.

to create a new map and assign it to a variable.

现在,为什么要打印 put 调用.

Now, why is the put call printed.

  1. 任何不在指令内的东西,比如 #set(notprint)#if(notprint)#foreach(again未打印),被打印,包括自由文本、变量和方法调用.

  1. Anything that is not inside a directive, like #set(not printed) or #if(not printed) or #foreach(again not printed), is printed, including free text, variables, and method calls.

Velocity 无法区分 $myMap.get('mykey')$myMap.put('key', 'value') (reader vs. writer),所以 put 调用的结果被打印出来,就像任何其他方法一样.

Velocity can't distinguish between the different semantics of $myMap.get('mykey') and $myMap.put('key', 'value') (reader vs. writer), so the result of the put call is printed, just like any other method.

每当某些东西无法正确求值时,因为变量未定义或某处方法返回 null,无法求值的代码会逐字转储到输出.

Whenever something can't be properly evaluated, because a variable is not defined or somewhere along the line a method returns null, the code that failed to be evaluated is dumped literally into the output.

正如 put 方法的文档所述,该函数返回为该键存储的先前值,如果根本没有设置值,则返回 null.

As the documentation of the put method states, the function returns the previous value stored for that key, or null if no value was set at all.

总结起来,打印那条线是正常的.

Summing it all up, it's normal to get that line printed.

要尝试这个理论,你可以这样做:

To try this theory out, you can do this:

#set ($myMap = {})
$myMap.put('key', 'first value')
$myMap.put('key', 'second value')
$myMap.get('key')

这将被打印:

$myMap.put('key', 'first value')
first value
second value

您可以做两件事来不打印该行:

There are two things you can do so that the line isn't printed:

  1. 将函数的结果存储在一个临时变量中:#set ($discard = $myMap.put('key', 'value')

使用静默方法调用:$!myMap.put('key', 'value')

我推荐第一个,因为当您替换现有值时,第二个仍然会打印一些内容.

I'd recommend the first one, since the second one will still print something when you're replacing an existing value.

这篇关于速度模板引擎 - 键值映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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