Custom iterative tag in Grails with named variable

I will show you how to create an iterative Grails tag that can contain another tag. The inner tag will use variable of the iterative tag. So, we are going to implement a tag that creates n links ‘/show/1’, ‘/show/2’, etc. with description ‘Article number 1’, ‘Article number 2’ etc.:

First of all, there is a nice and handy example for a simple iterative tag on the Grails site.


def repeat = { attrs, body ->
  def i = Integer.valueOf( attrs["times"] )
  def current = 0
  i.times {
    // pass the current iteration as the groovy default arg "it"
    // then pass the result to "out" to send it to the view
    out << body( ++current )



Repeat this 3 times! Current repeat = ${it}

Slight modification of the tag does not lead to the requested functionality:

  Hello number  ${it} 

It just generates the "Article number" string three times, because the it variable is not known here.
Thus it is necessary to change the tag definition. Lets add another parameter vars as a symbolic name of the current member of the collection.

def repeat = { attrs, body -> 
  def pars = [:]

  attrs.times?.toInteger().times { n -> 
    pars[attrs.var] = n
    out << body(pars) 

And now it is possible to use g:link inside the custom tag:

  Hello number  ${num} 

I am not sure if it is supported, but it is definitely working.