What I will present below about i18n-asset-pipeline
grails plugin which is doing the same job as jquery.i18n.properties.js
as such. You probably find a few implementations of jquery.i18n.properties.js
on grails plugin portal. I’m not entirely sure you will be happy with my suggestion. However, I would say that using this plugin will help us minimise the effort to maintain and call tag lib g:message
in both grails views and external javascript files.
If you feel confident to play with i18n-asset-pipeline
, please take a closer look at its documentation. Below are the summarised baby steps I have been doing with grails 2.5.6
.
Step 1: Declare the plugin in BuildConfig.groovy
plugins {
...
runtime 'org.grails.plugins:i18n-asset-pipeline:1.0.6'
...
}
Step 2: Define your messages properties in the appropriate files
In Resource Bundle messages under grails-app/i18n
directory, you add your languages of interest files, such as messages_fr.properties
, messages_vi.properties
, etc. To demonstrate how this works, I have welcome.message
just display a welcome message on the index page in these files messages_{fr,es,vi}.properties
.
Step 3: Define i18n
files in assets/javascripts/i18n
directory
After starting the application first, you will see this directory. Creating the same set of files, i.e.,messages.i18n
messages_{es,fr,vi}.i18n
. Inside these files, we just put the properties that were added in messages_{es,fr,vi}.properties
files or the properties you want to display in only specific languages.
Step 4: Set the default language (optional)
Leaving the following snippet in grails-app/conf/spring/resources.groovy
file
beans = {
localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
defaultLocale = new Locale("fr", "FR")
java.util.Locale.setDefault(defaultLocale)
}
}
Step 5: How to use i18n plugin
In views, we can load i18n language default setting and display message properties something along those lines.
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Demo | BioModels</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="layout" content="main"/>
<script>
</script>
<g:set var="locale" value="${session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'}"/>
<asset:i18n locale="${locale}"/>
</head>
<body>
<h2><g:message code="welcome.message"/> </h2>
</body>
</html>
Step 6: Testing
Open a tab in your web browser, retrieving your page, http://localhost:8900/i18ndemo/demo/
, for instance, it will render the content of welcome.message
property in the default language which was set up in resources.groovy
. If you want to switch to other languages straightaway, type ?lang=es
after the previous URL. That looks like http://localhost:8900/i18ndemo/demo/?lang=es
After getting through those steps, I believe you will obtain your need.
The sample project has been also pushed to bitbucket found here.
I hope this answer would help you solve your problem.