Search code examples
apacheinterpolationvelocity

Apache Velocity Placeholder Interpolation


Maybe because it's Friday afternoon here in the UK, and my brain has decided to slow down in eager anticipation for the weekend, but I've gotten myself down a rabbit hole with Apache Velocity and i'm hoping one of you lovely people on the internet will be able to jump start my brain back up again.

My crazy use case is as follows:

#foreach( $item in $array )
    #set($myVariable = "#customDirective('a.key.with.the.${foreach.index}')")
#end

I have a for loop to iterate over a list, then for each item in that list I invoke a custom directive which takes a parameter which is a pre-defined key of which the loop index forms a part. I set the result of the custom directive to a variable so it can be used further down the line.

Now, I understand that anything inside the single quotes (') is treated as a literal, and anything inside the double quotes (") gets resolved. So what I see happening is that when I log out the input parameter in the custom directive, the ${foreach.index} has not been resolved to a value but instead treated as the string literal.

What is the correct way for me to construct my input parameter for the directive in this scenario?

I'm using Velocity version 2.0, but am able to upgrade or downgrade if need be.


Solution

  • On a Friday afternoon, better split the evaluation in two lines:

    #foreach( $item in $array )
        #set($arg = "a.key.with.the.${foreach.index}")
        #set($myVariable = "#foo($arg)")
    #end
    

    and leave the one-liners for Monday morning:

    #foreach( $item in $array )
        #set($myVariable = "#foo(""a.key.with.the.${foreach.index}"")")
    #end
    

    The rationale is that you need two levels of interpolation, so you need to escape (hence double) the inner double quotes.