Grails – Render method & Markup builder

During Graemes’ demo of Grails at javasummercamp he briefly pointed out the fact that one can implicitly use the Groovy MarkupBuilder (Similar to the Markaby DSL for Ruby) within the render method of an action for generating markup.

Which makes writing an RSS feed for you application really easy:

[groovy]
def feed = {
def results = Task.list(max: 10, sort: ‘id’, order: ‘desc’)
render(contentType: ‘application/rss+xml’) {
rss(version: ’2.0′) {
channel{
title(‘recent tasks’)
description(‘A feed of the 10 most recent tasks’)
link(‘/task/list’)
results.each { task ->
item{
title(task.subject)
description(task.description)
link(“/task/view/${task.id}”)
pubDate(new Date()) // might want to put something useful in here
}
}
}
}
}
}
[/groovy]

Which will result in something like this:

[xml]


A feed of the 10 most recent tasks

/task/list

After investigating the markupbuilder, use it to
create a simple RSS feed

/task/view/2 Sun Aug 26 15:06:43 CEST 2007

Investigate the MarkupBuilder

/task/view/1 Sun Aug 26 15:06:43 CEST 2007



[/xml]

Wonderful isn’t it?

Apart from this, it might be useful to know that Grails has build-in builders for JSon as well!

This entry was posted in grails, groovy, java. Bookmark the permalink.

2 Responses to Grails – Render method & Markup builder

  1. Sebastian Kurt says:

    nice example, thanks! but it only works 90%, because link() errors with StackOverflow:
    http://markmail.org/message/msonhlrlpumtbi42

  2. peter says:

    Thanks for pointing this out! At the time I wrote this blog the above worked; I’ll update it!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>