简体   繁体   中英

Exposing message.properties to javascript?

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?

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.net/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM