Better i18n using the p:text tag from Grails Platform-Core

Posted by: on Aug 17, 2012 | No Comments

The Grails Platform Core plugin release 1.0.M3 added a new mechanism for rendering UI strings that is especially useful for plugins.

Note that there is a 1.0.M6 release now which is the recommended version.

The new p:text tag behaves very much like the Grails g:message tag.

The key difference is that the tag supports prefixing the message keys, and automatically applies a prefix based on the name of the plugin that supplied the GSP.

So where in the past you might have used g:message like this:

<g:message code="welcome.message"/>

You would now write:

<p:text code="welcome.message"/>

The difference here is that the new form will resolve the message welcome.message in an application, but if you were using it in a plugin called SuperUi it would resolve to plugin.superUi.welcome.message.

You may or may not have realised the problems with plugins polluting the i18n key namespace. At best it can be unclear what keys are used where, at worst you can find plugins using strings provided by other plugins or your app.

In all cases, using p:text you know that you are safe and don’t have to worry about choosing a prefix. It just works.

There’s a few other gems nestling in here. First, you can force a specific prefix using the p:textScope tag. So in your application’s edit page you might want all keys to use the “edit.” prefix:

<p:textScope scope="forms.edit"/>
<h1><p:text code="page.heading"/></h1>
<p><p:text code="page.intro"/></p>

You can also use this to masquerade as a plugin when you’ve overridden a plugin’s GSP (see docs).

Another trick: support for multiple codes. As well as the error attribute like that supported in g:message, the codes attribute supports resolving a list of codes to find the first match.

Last of all: default strings can be specified as the body of the tag, which can be more convenient for apps that don’t want to define i18n strings yet, but would like them to be supported in future.

This new mechanism for resolving i18n strings is used throughout platform-core’s tags, and another post will show some other examples of how this works in p:button, p:label, and p:smartLink.