Skip to content

Instantly share code, notes, and snippets.

@sergiomichels
Last active December 20, 2015 03:29
Show Gist options
  • Select an option

  • Save sergiomichels/6063861 to your computer and use it in GitHub Desktop.

Select an option

Save sergiomichels/6063861 to your computer and use it in GitHub Desktop.
Generating JavaScript from a Grails controller
class JavaScriptController {
def i18NService
/**
* Render dynamic JavaScript to the browser. It can be used in a GSP as:
*
* <script type='text/javascript' src='${createLink(controller: "javaScript", action: "scripts")}'></script>
*
* You can access i18n messages in javascript with window.messages variable. Example:
*
* alert(window.messages['my.message.key']);
*
*/
def scripts() {
Locale locale = RequestContextUtils.getLocale(request)
String messages = i18NService.messagesToJavaScript(locale)
//if you're using JQuery, check http://api.jquery.com/jQuery.parseJSON/
//String content = "I18N.messages = $.parseJSON('$messages');"
//For old browsers check http://stackoverflow.com/questions/4430472/how-do-i-use-json-in-older-browsers
String content = "I18N = {}; \n I18N.messages = JSON.parse('$messages');"
render contentType: 'text/javascript', text: content
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment