Last active
December 20, 2015 03:29
-
-
Save sergiomichels/6063861 to your computer and use it in GitHub Desktop.
Generating JavaScript from a Grails controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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