Java Velocity foreach 循环
我有一个 ArrayList,它在 java 中填充并将其传递给速度模板以供使用。现在,当我尝试迭代列表并从列表中创建一个“逗号”分隔的字符串时,我观察到一种不稳定的行为。
以下是我的代码
> #set($list_str="")
> #foreach($item in $list)
> #set($list_str=$!list_str+$!item+",")
> #end
现在我看到我的变量 $list_str 具有列表的所有元素,但最后还附加了迭代器“$!item”的变量名称。
所以,假设我的列表有 [0,1,2,3,4],我的最终结果($list_str 的值)是 [0,1,2,3,4],$!item, 我不确定
这是否是因为列表中的空引用被填充并传递给速度模板。
任何有关解决此问题的指示将不胜感激。
谢谢
I have an ArrayList that im populating within java and passing it off to a velocity template for consumption. Now when i try iterating the list and creating a 'comma' separated string from the list, Im observing an erratic behavior.
The following is my code
> #set($list_str="")
> #foreach($item in $list)
> #set($list_str=$!list_str+$!item+",")
> #end
Now i see that my variable $list_str has all the elements of the list but at the end the variable name of the iterator '$!item' is also being appended.
So, say my list has [0,1,2,3,4], my end result(value of $list_str) is [0,1,2,3,4],$!item,
Im not sure if this is because of a null reference from within the list being populated and being passed to the velocity template.
Any pointers towards fixing this would be greatly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我快速检查了一下,这似乎是因为 ArrayList 中存在空值。
对于如下所示填充的 ArrayList -
以及速度代码如下 -
我得到以下输出 -
这似乎符合预期。
现在,当我如下填充我的 Arraylist 时——
并且使用与上面相同的速度代码,我得到以下输出——
所以,我猜测您需要在代码中的某处添加空检查以避免这种情况。
谢谢
p1nG
PS:正如@Thilo 所指出的,我不确定括号来自哪里,不确定这是否是所需的行为。
I did a quick check and this seems to be because of a null value in your ArrayList.
For an ArrayList populated as below --
and with a velocity code as below --
I get the following output --
which seems to be as expected.
Now when i populate my Arraylist as follows --
and with the same velocty code as above, i get the following output --
So , im guessing that you need to add a null check somewhere in your code to avoid this.
Thanks
p1nG
PS: As pointed out by @Thilo Im not sure where the brackets are from, not sure if this is the desired behavior.
使用速度工具来执行此操作
例如,
就是这样,结果将是 nando,bob,don
如果您在列表方法中不包含第二个参数,则会得到
南多、鲍勃和唐
Use the velocity tools to do this
eg
Thats it the result will be nando,bob,don
if you dont include the second parameter in the list method you get
nando,bob and don