如何在Google Closure中进行本地化 [英] How to do localization in Google Closure
问题描述
当前,我在Closure应用程序中仅使用纯文本.我想在这些文本中添加本地化.我刚刚找到了几篇有关goog.getMsg函数的文章,该文章用于进行这种本地化.据我了解,它是在编译时完成的.用户单击按钮时,如何在运行时更改语言?使用Closure最简单的方法是什么?
Currently I am using just plain text in my Closure application. I want to add localizations to those text. I just found several articles about goog.getMsg function which is used to do this kind of localization. As far as I understood it is done in compile time. How can we change language in run-time when user clicks a button? What is the easiest way to do this using Closure?
推荐答案
我实际上已经实现了运行时i18n.我在其中使用
I have actually achieved a runtime i18n. I use .soy templates with {msg}
tags in them. When you compile .soy to .js, these calls get compiled to goog.getMsg calls. What I had to do was:
- 找到其中所有包含
goog.getMsg(
的所有.js
文件 - 添加
goog.require("myApp.i18n");\n
- 将所有
goog.getMsg(
呼叫替换为myApp.i18n.translate(
- 将所有
MSG_*
属性名称替换为myprefix_MSG_*
- Find all
.js
files that hadgoog.getMsg(
in them - Prepend
goog.require("myApp.i18n");\n
- Replace all
goog.getMsg(
calls withmyApp.i18n.translate(
- Replace all
MSG_*
property names withmyprefix_MSG_*
为什么所有这些:一个人不能直接覆盖goog.getMsg,因为它被认为是编译器原语,并且不允许任何操作. MSG_*
属性也是如此.
Why all this: One cannot override goog.getMsg directly, because it is considered a compiler primitive and does not allow any manipulation whatsoever. Same applies for MSG_*
properties.
myApp.i18n.translate
是一个接受字符串的函数,尝试在语言环境映射(在运行时传递)中查找它,并使用本地化的字符串返回goog.getMsg
结果(goog.getMsg
做一些方便的占位符替换).
myApp.i18n.translate
is a function that accepts string, tries to look it up in a locale map (which is passed in runtime) and returns goog.getMsg
result using the localized string (goog.getMsg
does some handy placeholder replacements).
虽然这不是一个非常漂亮的解决方案,但是它可以工作,并且允许我在运行时更改语言,仅对所有语言使用一个编译文件.
While this is not a very pretty solution, it works and allows me to change language in runtime, using only one compiled file for all languages.
实际的代码包含一些技巧,这些技巧使我可以使用生成的描述并使用JSON文件而不是看上去很奇怪的闭包文件格式,但是要旨是相同的.
The actual code includes a few hacks that allows me to use the generated description and use JSON files instead of the strange-looking closure file format, but the gist is the same.
您真正应该做的是从您的应用中编译多个文件,并为每种语言加载不同的.js文件.
我必须使用此解决方案,因为我需要支持数百种不同的配置和多种语言:当一次编译花费30秒钟以上的时间时,编译成千上万个.js文件会很疯狂.
I had to use this solution, because I need to support hundreds of different configurations and several languages: it would be insane to compile thousands of .js files, when one compilation takes 30+ seconds.
这篇关于如何在Google Closure中进行本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!