How to define function binding inside a GStringTemplateEngine template?

I would like to define a function that will be used in templates for GStringTemplateEngine. I tried using binding:

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 does not work. The pattern engine seems to close the closures in the bindings with logical ones. How should I do it? Or maybe I should choose a different template engine?

+5
source share
1 answer

Change index.tpl index to:

Var: ${var}
Prettified: <% print prettify.call(var) %>

will result in:

***test***Var: test
Prettified:

If you change index.tpl to:

Var: ${var}
Prettified: ${prettify.call(var)}

Conclusion:

Var: test
Prettified: ***test***
+6
source

All Articles