admin管理员组

文章数量:1415484

Is there an easy way to expose all translated strings to javascript? I want to be able to use translated strings in my JS files without manually building them in GSPs.

Is there an easy way to do this?

Is there an easy way to expose all translated strings to javascript? I want to be able to use translated strings in my JS files without manually building them in GSPs.

Is there an easy way to do this?

Share Improve this question asked Jun 2, 2011 at 17:17 Stefan KendallStefan Kendall 67.9k69 gold badges258 silver badges409 bronze badges 1
  • Just to add a valuable introductional link that uses the above JAWR as grails plugin: mrhaki.blogspot.de/2011/11/… – matcauthon Commented Aug 21, 2012 at 11:56
Add a ment  | 

2 Answers 2

Reset to default 6

The Jawr plugin (good plugin to use to optimize your JS and CSS resources anyway) can expose parts or the whole of your i18n message bundles to Javascript:

http://jawr.java/docs/messages_gen.html

Expose i18n/messages.properties as JSON

I18nController.groovy

package myproject

import grails.converters.JSON
import grails.plugin.springsecurity.annotation.Secured

@Secured("permitAll")
class I18nController {
  static defaultAction = "index"

  I18nService i18nService

  def index() {
    render i18nService.getAllTranslations(params, request) as JSON
  }
}

I18nService.groovy

package myproject

import grails.transaction.Transactional
import grails.web.servlet.mvc.GrailsParameterMap
import org.springframework.context.MessageSource

import javax.servlet.http.HttpServletRequest

@Transactional
class I18nService {

  MessageSource messageSource
  LocaleService localeService

  /**
   * http://www.razum.si/blog/grails-javascript-i18n-messages
   * @return
   */
  Properties getAllTranslations(GrailsParameterMap params, HttpServletRequest request) {
    Locale locale = localeService.prepareLocale(params, request)
    Properties keys = messageSource.withTraits(MessagePropertiesTrait).getMessageKeys(locale)

    //def jsKeys = keys.findAll { code, value -> ((String) code).startsWith('js.') }
    //render jsKeys as JSON

    return keys
  }
}

LocaleService.groovy

package myproject

import grails.transaction.Transactional
import grails.web.servlet.mvc.GrailsParameterMap
import org.springframework.web.servlet.support.RequestContextUtils

import javax.servlet.http.HttpServletRequest

@Transactional
class LocaleService {

  public static final String DEFAULT_LANG = 'es'
  public static final String PARAM_LANG_KEY = 'langKey'
  public static final String COOKIE_LANG_KEY = 'language'

  Locale prepareLocale(GrailsParameterMap params, HttpServletRequest request) {
    Locale locale = null
    int i = 0

    List<String> langStrings = new ArrayList<>()
    langStrings.add(params.get(PARAM_LANG_KEY) as String)
    langStrings.add(request.cookies.find { COOKIE_LANG_KEY == it.name }?.value)

    while ((locale == null) && (i < langStrings.size())) {
      String str = langStrings.get(i)
      if (str) {
        try {
          locale = new Locale(str)
        } catch (Exception ex) {
          ex.printStackTrace()
        }
      }

      i++
    }

    if (locale == null) {
      try {
        // From Request
        locale = RequestContextUtils.getLocale(request)
      } catch (Exception e) {
        // Default
        locale = new Locale(DEFAULT_LANG)
      }
    }

    return locale
  }
}

Helpers.groovy

Create this file at utils/myproject:

package myproject

import groovy.transform.CompileStatic
import groovy.transform.TypeCheckingMode

@CompileStatic(TypeCheckingMode.SKIP)
trait MessagePropertiesTrait {
  Properties getMessageKeys(Locale locale) {
    this.getMergedProperties(locale).properties
  }

  Properties getPluginMessageKeys(Locale locale) {
    this.getMergedPluginProperties(locale).properties
  }
}

UrlMappings.groovy

Add follow URL mapping:

"/i18n/$langKey?(.$format)?"(controller: 'i18n', action: 'index')

Usage

URL

http://localhost:8080/i18n # Default language
http://localhost:8080/i18n/.json # Default language

http://localhost:8080/i18n/en.json
http://localhost:8080/i18n/en

http://localhost:8080/i18n/es.json
http://localhost:8080/i18n/es

Cookie

Set a Cookie named language with the language (es, en, ...) and call http://localhost:8080/i18n or http://localhost:8080/i18n/.json

本文标签: grailsExposing messageproperties to javascriptStack Overflow