Reputation: 2427
This is pretty common in Java-world having properties files with dot (.) in the key. Maven and Gradle solves this problem naturally but now I need to do this in plain groovy:
def propertiesFileContent = 'a.b=http://my.com/test'
def templateContent = 'Testing ${a.b} '
def props = new Properties()
props.load(new StringReader(propertiesFileContent))
def template = new groovy.text.SimpleTemplateEngine().createTemplate(templateContent)
println template.make(props)
The above code throws exception because the template engine threats ${a.b} as 'b' field of the 'a' object and do not accept 'a.b=http://my.com/test' to substitute. First I thought it is a bug in groovy templating but now it seems that this is a well-known limitation, and everybody suggests solutions that needs the modification of the template:
I'm in a situation where I should do this without the chance to modify the properties file or the template itself: they are in TAGged and released version of the application :-( Is there a solution or workaround if those are not possible? (I tried to use FreeMarker templating but facing the same issue)
Upvotes: 1
Views: 1148
Reputation: 1530
Take a look at groovy.util.ConfigSlurper#parse(java.util.Properties)
. Usage:
template.make(new ConfigSlurper().parse(props))
template.make()
expects an object containing template properties, for example:
[a: [b: 'http://my.com/test']]
ConfigSlurper
does exactly what is needed converting Properties
instance to such an object.
Upvotes: 3