Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

vtl - Create and iterate through an array in Velocity Template Language

How to create an array in VTL and add contents to the array? Also how to retrieve the contents of the array by index?

question from:https://stackoverflow.com/questions/6123691/create-and-iterate-through-an-array-in-velocity-template-language

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to Apache Velocity User Guide, right hand side of assignments can be of type

  • Variable reference
  • List item
  • String literal
  • Property reference
  • Method reference
  • Number literal
  • ArrayList
  • Map

You can create an empty list, which would satisfy all your needs for an array, in an Apache Velocity template with an expression like:

#set($foo = [])

or initialize values:

#set($foo = [42, "a string", 21, $myVar])

then, add elements using the Java add method:

$foo.add(53);
$foo.add("another string");

but beware, as the Java .add() method for the list type returns a boolean value, when you add an element to the list, Velocity will print, for instance, "true" or "false" based on the result of the "add" function.

A simple work around is assigning the result of the add function to a variable:

#set($bar = $foo.add(42))

You can access the elements of the list using index numbers:

<span>$foo[1]</span>

Expression above would show a span with the text "a string". However the safest way to access elements of a list is using foreach loops.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...