Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define function binding inside GStringTemplateEngine template?

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?

like image 884
Soid Avatar asked Mar 05 '13 03:03

Soid


1 Answers

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***
like image 116
jocki Avatar answered Nov 07 '22 17:11

jocki