Matty Balaam
Matty Balaam

Reputation: 1309

creating array and using in a for loop

I am wondering if it is possible to an array similar to:

#set ( $foo1 = [ 
  $title, 'some title', 
  $text, 'some text'
]

#set ( $foo2 = [ 
  $title, 'different title', 
  $text, 'different text'
]

with the aim of then looping through code like this

#foreach($i in [1..2])

<div id="$i">
  <h1>$foo$i.title<h1>
  <p>$foo$i.text</p>
</div>

#end

I seem to have two problems I can't figure out a solution to. I have been able to set an array, but I have only been successful using a number index rather than a variable name.

My second problem is maybe related to Velocity only parsing once. Even a simple example like:

#set ( $foo1 = "bar" )
#set ( $foo2 = "bar2" )

#foreach($i in [1..2])
  $foo$i ---
#end

Will only parse to $foo1 --- $foo2

Is it possible to do what I wish to achieve, and how might I be able to adapt my code. If I have to only use a number index in my array that is OK, so I guess the more pressing problem is how to dynamically change the variable through each loop.

Upvotes: 0

Views: 72

Answers (1)

Matty Balaam
Matty Balaam

Reputation: 1309

After finding a couple of people with Velocity knowledge I was able to crack this.

#set ( $foo1 = { 
  "title": "some title", 
  "text": "some text"
]

#set ( $foo2 = [ 
  "title" "different title", 
  "text", "different text"
]

#set ( $foos = [$foo1, $foo2] )

#foreach($foo in $foos)

<div id="$velocityCount">
  <h1>$title<h1>
  <p>$text</p>
</div>

#end

Upvotes: 0

Related Questions