I would like to define a function to be used in templates for GStringTemplateEngine. I tried to use binding like that:
import groovy.text.GStringTemplateEngine
def prettify = {
return "***${it}***"
}
def var = "test"
def f = new File('index.tpl')
engine = new GStringTemplateEngine()
tpl = engine.createTemplate(f).make([
"var": var,
"prettify": prettify
])
print tpl.toString()
index.tpl:
Var: ${var}
Prettified: <% print prettify(var) %>
It throws an exception:
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.tmp.templates.GStringTemplateScript1.prettify() is applicable for argument types: (java.lang.String) values: [test]
Possible solutions: notify(), printf(java.lang.String, [Ljava.lang.Object;), printf(java.lang.String, java.lang.Object), printf(java.lang.String, [Ljava.lang.Object;), identity(groovy.lang.Closure), printf(java.lang.String, java.lang.Object)
But it's not working. Looks like the template engine casts closures in bindings to boolean. How do I do it? Or probably I should pick another template engine?
Changing your index.tpl into:
Var: ${var}
Prettified: <% print prettify.call(var) %>
Will result in:
***test***Var: test
Prettified:
If you change your index.tpl into:
Var: ${var}
Prettified: ${prettify.call(var)}
The output is:
Var: test
Prettified: ***test***
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With