(Quick Reference)

6.3.2 简单标签 - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

6.3.2 简单标签

As demonstrated it the previous example it is easy to write simple tags that have no body and just output content. Another example is a dateFormat style tag:

def dateFormat = { attrs, body ->
    out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}

The above uses Java's SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a GSP as follows:

<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:

def formatBook = { attrs, body ->
    out << "<div id="${attrs.book.id}">"
    out << "Title : ${attrs.book.title}"
    out << "</div>"
}

Although this approach may be tempting it is not very clean. A better approach would be to reuse the render tag:

def formatBook = { attrs, body ->
    out << render(template: "bookTemplate", model: [book: attrs.book])
}

And then have a separate GSP template that does the actual rendering.

正如以前示例所演示的那样,要写一个只输出内容而没有主体(body)的标签是很容易的。另外的一个示例是dateFormat风格的标签:

def dateFormat = { attrs, body ->
    out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}

在上例中,使用了Java的SimpleDateFormat类来格式化一个日期,并且将它写回到响应中。然后标签就可以在GSP中像下面所示那样使用:

<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

在简单标签中,有时候需要你将HTML标记内容写回响应。一种方法是直接将内容内嵌到标签中:

def formatBook = { attrs, body ->
    out << "<div id="${attrs.book.id}">"
    out << "Title : ${attrs.book.title}"
    out << "</div>"
}

虽然此种方式很直接诱人,但是很不简洁。更好的一种方式是复用render标签:

def formatBook = { attrs, body ->
    out << render(template: "bookTemplate", model: [book: attrs.book])
}

这样就分离出一个GSP模板来处理真正的渲染。