6.3.4 Iterative Tags - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
6.3.4 Iterative Tags
Iterative tags are easy too, since you can invoke the body multiple times:
Las etiquetas iterativas son tambien sencillas, pues puedes invocar el cuerpo multiples veces:def repeat = { attrs, body ->
attrs.times?.toInteger()?.times { num ->
out << body(num)
}
}
In this example we check for a
En este ejemplo podemos buscar el atributo times attribute and if it exists convert it to a number, then use Groovy's times method to iterate the specified number of times:
times y si existe convertirlo en un numero, entonces usar el metodo times de Groovy para iterar en un numero especifico de veces:<g:repeat times="3"> <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>
Notice how in this example we use the implicit
Note como en este ejemplo usamos la variable implicita it variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:
it para referirnos al numero actual. Esto funciona porque cuando invocamos el cuerpo le pasamos el valor actual dentro de la iteracion:out << body(num)
That value is then passed as the default variable
Ese valor es pasado entonces como la variable it to the tag. However, if you have nested tags this can lead to conflicts, so you should should instead name the variables that the body uses:
it por defecto hacia la etiqueta. Sin embargo, si has anidado etiquetas esto puede ocasionar conflictos, asi que en ves deberia de nombrar las variables que el cuerpo usa:def repeat = { attrs, body ->
def var = attrs.var ?: "num"
attrs.times?.toInteger()?.times { num ->
out << body((var):num)
}
}
Here we check if there is a
Aqui checamos si hay un atributo var attribute and if there is use that as the name to pass into the body invocation on this line:
var y si lo hay lo usamos como el nombre para pasarlo dentro de la invocacion del cuerpo en esta linea:out << body((var):num)Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself.
Note el uso del parentesis alrededor del nombre de la variable. Si usted omite esto Grovvy asume que esta usando una llave String y no se esta refiriendo a la variable.
Now we can change the usage of the tag as follows:
Ahora podemos cambiar el uso de la etiqueta como sigue:<g:repeat times="3" var="j"> <p>Repeat this 3 times! Current repeat = ${j}</p> </g:repeat>
Notice how we use the
Note como usamos el atributo var attribute to define the name of the variable j and then we are able to reference that variable within the body of the tag.
var para definir el nombre de la variable j y entonces somos capaces de referenciar la variable dentro del cuerpo de la etiqueta.

