user3334236
user3334236

Reputation: 21

Accessing properties in templates by their name

given the following pieces of code:

groovy:

binding = [key1: "val1"]
def f = new File('test.template')
engine = new GStringTemplateEngine()
template = engine.createTemplate(f).make(binding)
println template.toString()

test.template:

<% keyName = "key1" %>

Is there a way to access val1 by keyName in test.template?

This:

${ binding[keyName] }

does not work (No such property: key1 for class: groovy.lang.Binding). Any ideas? Maybe the name of the map holding the properties is different?

I know I could just write:

${ key1 }

but I need to access property key1 using variable keyName.

Upvotes: 2

Views: 784

Answers (1)

mikemil
mikemil

Reputation: 1241

Not sure if this is better but I got the following to work (somewhat)

Map binding = [ keyName: 'key1', key1: "val1", m: [key1:'val100', key2:'val2']]
def f = new File('test.template')
def engine = new groovy.text.GStringTemplateEngine()
def template = engine.createTemplate(f).make(binding)
println template.toString()

with the following template:

$keyName
$key1
<%= m[keyName] %>

But this relies on a submap that holds the values you are looking for.

I can see scenarios where in the binding, you pass a list of fields you want to process or display (rather than knowing them ahead of time), so you would have to get the field names from a well-known variable and then process the others possibly thru a submap.

Upvotes: 1

Related Questions