Grails templating & Ajax

Grails' templating system is cool. There is no doubt about it. It's what I wanted JSP2.0 tagfiles to be. In essence they're not so different from tagfiles in practice their versatility is a fair bit higher.

Templates in Grails reside in the views folder of your project, and are plain gsp files prefixed with an underscore (i.e. /views/task/_task.gsp). The can contain anything a gsp template can.

So, say we have a simple template called _textile.gsp:

HTML:
  1. <div class="textileText">
  2.     <g:textile text="${text}"/>
  3. </div>

It can be rendered in a view using the render tag like this:

HTML:
  1. <g:render template="textile" var="text" bean="${task.description}"/>

Or, using an iterator:

HTML:
  1. <g:render template="textile" var="text" collection="${task?.comments}" />

Verry nice, you'll probably say... but I can easily do that using a JSP tag as well. True. Enter the fact that you can call a template from your controller as well:

GROOVY:
  1. def textilePreview = {
  2.     render(template: "textile", var: "text", bean: params.text)
  3. }

This is specifically useful when Ajax is put into the equation, since it creates a simple framework to create templates to be used for re-rendering parts of the page after the page has loaded:

HTML:
  1. <!-- snip -->
  2. <g:remoteTextArea id="description" action="textilePreview" update="descPreview" paramName="text" name='description' cols="240" value="${task?.description}"/>
  3.  
  4. <div id="descPreview">
  5.     <g:render template="textile" var="text" bean="${task.description}"/>
  6. </div>

The remoteTextara (an adapted version of the standard remoteField tag) fires Ajax calls to the textilePreview action, and the response is writen in de 'descPreview' div (specified by the 'update' attribute). Nice!

When I find some time I'll try and put a short video in, screenshots of dynamic updates are just a bit sad ;)


0 Responses to “Grails templating & Ajax”

  1. No Comments

Leave a Reply





About

Welcome to the weblog of Peter Maas. Here you'll find various posts related to stuff I like (like my kids and espresso) and stuff I do (like developing software).

JavaOne 2008 Pictures

raadhuis_trap IMG_4571 robin_met_zijn_hyundai_horloge_foon nog één stapje naar achteren Sjoerd met speer konijn IMG_4707.JPG sjoerd op klimrek Charles Nutter on JRuby IMG_4602 brug IMG_4599 maan golden_gate_warning_sign nemo pub IMG_6130 heart
View more photos >

Categories



Meld u aan voor PayPal en begin direct met het accepteren van creditcardbetalingen.