Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Velocity - Passing current forloop variable to another template

Tags:

java

velocity

I have a Velocity template where I am using a for loop and within it, executing a parse statement. The problem is the parse statement needs access to the current object in the for loop but it seems to go out of scope. Having searched on here, I tried one suggestion to create a variable and assign the current variable in the iteration to it, but it only works for the first iteration. All subsequent iterations contain a reference to the first object in the iteration. An example:

  #foreach ($someObject in $MyList)
       #set($anotherObject=$someObject)
       #parse('innerTemplate.vm')
  #end

The problem is innerTemplate.vm never sees $someObject, so if I assign it to another variable using the set construct, it only remembers the first item in the list.

like image 396
FuzzyLogic Avatar asked Oct 17 '11 08:10

FuzzyLogic


People also ask

How do you declare a variable in Velocity?

Depending on what is added to the Velocity Context (MagicDraw automatically adds its element to the Velocity Context) the variable can either be a local variable or a reference to a Java object. To declare a local variable inside a template, type: $ followed by a string beginning with a letter.

What is Velocity .VM file?

Developer file used by Velocity, a Java-based template engine; written using the Velocity Template Language (VTL); contains VTL statements inserted in a normal text document; often used for auto-generating Web source code and class skeletons.

Is Apache Velocity deprecated?

Well, the reason is that the Velocity Engine has been deprecated for a while, and a lot of developers around the world need to find well-fitting alternatives. Let's begin and define the set for our test. We will compare the following engines: Apache Velocity.

How do you add numbers in Velocity template?

You would typically do something like #set ($oldIndex = $number. toNumber($oldIndex)) if you have the NumberTool present in your context, for instance. And that's it, $oldIndex contains an integer! Please note that the Integer.


1 Answers

Velocity already provides a way to get the loop count through $velocityCount.

Try this:

outerTemplate.vm:

#foreach ($someObject in $MyList)
   #parse('innerTemplate.vm')
#end

innerTemplate:

$velocityCount
like image 96
Francisco Paulo Avatar answered Sep 22 '22 04:09

Francisco Paulo