Groovy templates variable passing

May 9, 2018 programming

Groovy Templates is one of the new cool kids on the block. It enables you to ditch the stinky old templates like FreeMarker or Velocity and use groovy to write your templates, which basically means no more eyes bleeding from angled brackets and HTML syntax. You can check it out here. One of the issues that I was facing with the templates was trying to pass a variable in the groovy context to an included template. Let me give an example to make it clear

modelAndView.addObject("myvar", 5)
...


main.tpl:

div {
 include template 'included.tpl'
}


included.tpl:
 yield myvar

You add a variable to your model and have it rendered from the included template. The result is as expected this

<div>myvar</div>

But let’s say that myvar was a list of items that you wanted to iterate. Then the template code will be something like

main.tpl:

div {
 myvars.each { myvar ->
   include template 'included.tpl'
 }
}


included.tpl:
 yield myvar

Now you would expect it to render the contents of “myvar” in the included template but this will not happen. Instead you will get an error saying myvar is null. There is a kind of hack that I came up with to make this work and it’s to use the fragment directive. So the template becomes something like this

div {
 myvars.each { myvar ->
   fragment "include template: 'included.tpl'", myvar:myvar
 }
}

this passes the variable to the included template model context.