Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, September 7, 2011

Setting a Play! Framework Title from a Messages File

If you're working with Play! Framework Messages resources in Javascript, use the template tag {i18n /} to load fill a data structure with the contents of the messages file.  However, if you'd like to render a message title using the default layout, append a call to the messages.get() method.

Update: In a previous version, I wrote that the Messages.get() to retrieve an internationalized message required a fully-qualified path to the Messages class.  There is an implicit object 'messages' which is less verbose and consistent with other template code.

In order to internationalize your application, store message resources -- labels, titles, etc. -- in a separate, language-specific file.  Even if internationalization isn't a top priority, it's still beneficial to centralize the messages so they can be checked for consistency.

In the Play! Framework, the default layout will use the #{get} template tag to retrieve a page-specific title.  From the generated layout page

<title>#{get 'title' /}</title>

 An example page might define a title like this

<title>#{set 'title': 'My App' /}</title>

 Alternatively, the title can be added to a message resources file like this

# screen messages
app.title=My App

 Which can be applied to the #{set} tag as follows

  <title>#{set 'title': messages.get("app.title") /}

The output for both #{set} examples is

Play! Title from Messages File
 The get() call to on the implicit object 'messages' will support the current locale which is far better than hardcoding a string in the title.  The title can also reference messages that are parameterized using %s.  This might be used to provide a sub navigation key like "My App - Contacts" where a messages file contains the string "app.title=My App - %s".

No comments:

Post a Comment