Irm*_*mak 48
根据Apache Velocity用户指南,分配的右侧可以是类型
您可以在Apache Velocity模板中创建一个空列表,该列表将满足您对数组的所有需求,其表达式如下:
#set($foo = [])
Run Code Online (Sandbox Code Playgroud)
或初始化值:
#set($foo = [42, "a string", 21, $myVar])
Run Code Online (Sandbox Code Playgroud)
然后,使用Java add方法添加元素:
$foo.add(53);
$foo.add("another string");
Run Code Online (Sandbox Code Playgroud)
但请注意,由于列表类型的Java .add()方法返回一个布尔值,当您向列表中添加元素时,Velocity将根据"结果"打印,例如"true"或"false".添加"功能.
一个简单的解决方法是将add函数的结果赋给变量:
#set($bar = $foo.add(42))
Run Code Online (Sandbox Code Playgroud)
您可以使用索引号访问列表的元素:
<span>$foo[1]</span>
Run Code Online (Sandbox Code Playgroud)
上面的表达式将显示带有文本"a string"的跨度.但是,访问列表元素的最安全方法是使用foreach循环.
创建数组很简单:
#set($array = [])
Run Code Online (Sandbox Code Playgroud)
将元素放入数组也很容易:
$array.add(23)
Run Code Online (Sandbox Code Playgroud)
从数组中获取元素取决于您的Velocity版本.在Velocity 1.6中你必须使用
$array.get($index)
Run Code Online (Sandbox Code Playgroud)
从Velocity 1.7开始,您可以使用经典形式:
$array[$index]
Run Code Online (Sandbox Code Playgroud)
我没有在VTL中创建数组,而是将数组传递到VTL上下文并使用它们。在VTL中,您不能通过索引检索数组内容,您只能使用foreach,例如,此代码是从我的动态SQL生成VTL脚本复制的:
#foreach( $col in $Columns ) SUM($col.DBColumn) AS ''$col.Name''#if($velocityCount!=$Columns.Count), #end #end
Run Code Online (Sandbox Code Playgroud)
因此,我们也不能有二维数组。当我需要一个数组来连续存储 2 个对象时,我使用了定义一个新类并将该类的对象放入一维数组中的解决方法。
| 归档时间: |
|
| 查看次数: |
54643 次 |
| 最近记录: |