如何在JS中翻译字符串 [英] How to translate strings in JS

查看:140
本文介绍了如何在JS中翻译字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,我想将其翻译成多种语言的PHP部分我使用Zend Frameworks Zend_Translate和GetText。现在我也要翻译JS部分。

I have a project which I want to translate into multiple languages for the PHP Part I use Zend Frameworks Zend_Translate with GetText. Now I want to translate the JS part too.

我正在使用jQuery JS Framework,并且很想听听你对JS文件翻译的看法

I am using the jQuery JS Framework and would love to hear your thoughts on translation for JS files

推荐答案

我已成功使用GetText在三个项目中翻译JavaScript文件。

I have successfully used GetText for translation of JavaScript files in three projects.

当然GetText本身不支持JavaScript,JavaScript也不支持GetText。我的解决方案如下。

Of course GetText natively doesn't support JavaScript and JavaScript also doesn't support GetText. My solution has been the following.


  • 在JavaScript中我用 gettext(你的文字在这里)环绕可翻译的字符串

  • 然后我有一个脚本从JavaScript文件中提取字符串并创建一个C文件,因为gettext支持C.

  • 然后我在生成的C文件和项目中的任何其他文件上使用 xgettext 来生成POT和PO文件。

  • In JavaScript I surround translatable strings with gettext("your text here").
  • Then I have a script that pulls the strings out of JavaScript files and creates a C file, because C is supported by gettext.
  • Then I use xgettext on the generated C files and on any other files in my project to produce POT and PO files.

翻译PO文件后,我必须将翻译恢复为JavaScript ...

After translating PO files, I have to get the translations back to JavaScript...


  • 我再次解析JavaScript文件,记住可翻译字符串的列表,然后是每个语言环境:

  • 使用支持GetText的语言(在我的情况下是PHP)我翻译所有字符串和输出JavaScript文件。

例如爱沙尼亚语的语言环境文件(例如 et_EE.js )可能如下所示:

For example a locale file for Estonian (e.g. et_EE.js) might look like this:

var LOCALE = {
  "Hello": "Tere",
  "My name is %s": "Minu nimi on %s",
  "Enter your credit card number": "Sisesta oma krediitkaardi number"
};

function gettext(string) {
  return LOCALE[string] ? LOCALE[string] : string;
}

根据所选的区域设置,您可以包含 et_EE。 js en_US.js 或...

Depending on the selected locale you either include et_EE.js or en_US.js or ...

en_US.js 可能只包含以下内容:

en_US.js will probably contain just the following:

function gettext(string) {
  return string;
}

ngettext(),但你应该得到一般的想法。

A bit trickier for ngettext(), but you should get the general idea.

最棒的是我可以使用所有已有的gettext工具。特别是当我在PHP和JavaScript中都有可翻译的文本时 - 我可以使用相同的工具来翻译它们,并确保在JavaScript和PHP中以相同的方式翻译相同的字符串。

The great thing is that I can use all the gettext tools already available. Especially when I have translatable texts in both PHP and JavaScript - I can use the same tool for translating both of them and also ensure that the same string is translated the same way both in JavaScript and PHP.

注意:如果您没有使用JavaScript密集型网络应用,那么在首先使用JavaScript创建网页内容之前,您应该三思而行。

NOTE: If you aren't dealing with a JavaScript-intensive web-app, you should think twice before having page content created by JavaScript in the first place.

这篇关于如何在JS中翻译字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆