How to pass a bean or model to a template

12 / Sep / 2008 by Deepak 0 comments

When we want to render a view using a template and the template makes use of a model object, the model object needs to be passed to the template using GSP tags. I am writing this because it took me a while to figure this out. Thanks to the wonderful contributors on the mailing list who helped me with this.

To render the view to a template from a gsp we need to use this tag in your gsp

<g:render template=”/templateName”/>

To send a bean to the template we have to include  an attribute to the tag like this

<g:render template=”/templateName” bean=”beanName”/>

(or) we can also use a named variable in the template.For this we have to send a model

<g:render template="/templateName" model="beanName:${someBeanName}"/>

In the template we can use this by calling ‘it’  but that’s not my preferred way. The other way is, assign this value to a variable in the template like this.

<g:set var="variableName" value="${beanName}"/>

Now we can use the variableName in the template.

Example:

<input type="text" id="fieldId" class="${hasErrors(bean: variableName, field:
'fieldName', 'errors')}" name="fieldName" value="${fieldValue(bean: variableName,
field: 'fieldName')}"/>
FOUND THIS USEFUL? SHARE IT

Tag -

Grails Groovy gsp

Leave a Reply

Your email address will not be published. Required fields are marked *