16.3 Reading Messages

Reading Messages in the View

The most common place that you need messages is inside the view. Use the message tag for this:

  1. <g:message code="my.localized.content" />

As long as you have a key in your messages.properties (with appropriate locale suffix) such as the one below then Grails will look up the message:

  1. my.localized.content=Hola, me llamo John. Hoy es domingo.

Messages can also include arguments, for example:

  1. <g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />

The message declaration specifies positional parameters which are dynamically specified:

  1. my.localized.content=Hola, me llamo {0}. Hoy es {1}.

Reading Messages in Grails Artifacts with MessageSource

In a Grails artifact, you can inject messageSource and use the method getMessage with the arguments: message code, message arguments, default message and locale to retrieve a message.

  1. import org.springframework.context.MessageSource
  2. class MyappController {
  3. MessageSource messageSource
  4. def show() {
  5. def msg = messageSource.getMessage('my.localized.content', ['Juan', 'lunes'] as Object[], 'Default Message', request.locale)
  6. }

Reading Messages in Controllers and Tag Libraries with the Message Tag

Additionally, you can read a message inside Controllers and Tag Libraries with the Message Tag. However, using the message tag relies on GSP support which a Grails application may not necessarily have; e.g. a rest application.

In a controller, you can invoke tags as methods.

  1. def show() {
  2. def msg = message(code: "my.localized.content", args: ['Juan', 'lunes'])
  3. }

The same technique can be used in tag libraries, but if your tag library uses a custom namespace then you must prefix the call with g.:

  1. def myTag = { attrs, body ->
  2. def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes'])
  3. }