tags:

views:

190

answers:

1

I need to replace references (properties and methods) in the Velocity templates to some other values during template rendering. For example, from the template below:

___
I have $some text $daisy
#foreach ($someElement in $someCollection)
  #$someElement.doSomething()
#end
___

I need to get such text:

___
I have lalala1 text lalala1
lalala2
lalala2
lalala2
___

Besides, the reason is I don't know the names of references and the amount of them beforehand.

Well, technically, indeed I can open templates and manually look through, but I want to escape this way.

First of all, I tried to get references names from the template, working with implementation of ReferenceInsertionEventHandler, but the problem was in directives.

For example, with foreach I had exception "Could not determine type of iterator in #foreach loop" I looked through the velocity source code, I can change it as I need, but it will kill future project maintainability.

So the question is: is there any way to get all references names (properties and methods) from template and to change the values of them during rendering?

+1  A: 

I'm not sure if I completely understand your problem, but if you want to replace one variables with others (practically to do a consistent variable renaming), than you still need to know what variable with with what other variable name will replaced.

You can run the velocity templates as often as you like. E.g. in the first pass, you can replace e.g. $some with '$other', and in the second pass, to substitute $other with the final values you really want.

To get however all the variables in a template consistently (like in macros too), I saw that tools that rely on Velocity usually make use of modified versions of it's parser. E.g. in this case you would need to run a visitor over the AST Velocity creates from the template and collect the ASTVariables, but I think this is not an easy task.

An example might be this outdated example.

A. Ionescu
Thank you, that`s what I needed!