JavaScript 中的翻译就像 PHP 中的 gettext 一样?

发布于 2024-08-23 19:40:19 字数 104 浏览 5 评论 0原文

我在 PHP 代码中使用 gettext,但有一个大问题。我的所有 JavaScript 文件都不受翻译的影响,有人可以告诉我一种简单的方法,可以将所选语言的翻译也转换为 JavaScript。

I am using gettext in my PHP code, but I have a big problem. All my JavaScript files are not affected by the translation, can somebody tell me an easy way to get the translations in the chosen language into JavaScript as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

自演自醉 2024-08-30 19:40:19

最简单的方法是让 PHP 文件将 gettext 的翻译写入 JavaScript 变量。

js_lang.php:

word_hello = "<?php echo gettext("hello"); ?>"
word_world = "<?php echo gettext("world"); ?>"
word_how_are_you = "<?php echo gettext("how_are_you"); ?>"

然后包含它:

<script type="text/javascript" src="js_lang.php"></script>

我还会推荐此方法与 S.Mark 提到的翻译插件(非常有趣!)结合使用。

您也可以在当前页面的标题中定义字典,而无需包含外部文件,但这样,您就必须在每次页面加载时查找并发送数据 - 完全没有必要,因为字典往往很少更改。

The easiest way is having a PHP file write the translations from gettext into JavaScript variables.

js_lang.php:

word_hello = "<?php echo gettext("hello"); ?>"
word_world = "<?php echo gettext("world"); ?>"
word_how_are_you = "<?php echo gettext("how_are_you"); ?>"

and then include it:

<script type="text/javascript" src="js_lang.php"></script>

I would also recommend this method in conjunction with the translation plugins S.Mark mentions (which are very interesting!).

You can define the dictionary in the current page's header, too, without including an external file, but that way, you would have to look up and send the data on every page load - quite unnecessary, as a dictionary tends to change very rarely.

三生殊途 2024-08-30 19:40:19

我通常以 JavaScript 结构导出翻译:

var app = {};
var app.translations = {
  en: {
    hello: "Hello, World!",
    bye: "Goodbye!"
  },
  nl: {
    hello: "Hallo, Wereld!",
    bye: "Tot ziens!"
  }
};

可以使用以下方式定义页面文本的当前语言:

这可以读取在 JavaScript 中:

var currentLanguage = document.documentElement.lang || "en";
app.lang = app.translations[ currentLanguage ] || app.translations.en;

然后你可以编写这样的代码:

alert( app.lang.hello );

(可选)i18n()gettext() 函数可以带来一些智能,如果按键则返回默认文本不存在)。例如:

function gettext( key )
{
  return app.lang[ key ] || app.translations.en[ key ] || "{translation key not found: " + key + "}";
}

I generally export the translations in a JavaScript structure:

var app = {};
var app.translations = {
  en: {
    hello: "Hello, World!",
    bye: "Goodbye!"
  },
  nl: {
    hello: "Hallo, Wereld!",
    bye: "Tot ziens!"
  }
};

The current language of the page texts can be defined using: <html xml:lang="en" lang="nl">

This can be read in JavaScript:

var currentLanguage = document.documentElement.lang || "en";
app.lang = app.translations[ currentLanguage ] || app.translations.en;

And then you can write code like this:

alert( app.lang.hello );

Optionally, a i18n() or gettext() function can bring some intelligence, to return the default text if the key does not exist). For example:

function gettext( key )
{
  return app.lang[ key ] || app.translations.en[ key ] || "{translation key not found: " + key + "}";
}
半衾梦 2024-08-30 19:40:19

尝试 jQuery i18njQuery 本地化

jQuery i18n 的示例,当然您需要从 php 的语言文件生成基于 JSON 的字典

var my_dictionary = { 
    "some text"  : "a translation",
    "some more text"  : "another translation"
}
$.i18n.setDictionary(my_dictionary);


$('div#example').text($.i18n._('some text'));

Try, jQuery i18n or jQuery localisation

An example for jQuery i18n, and of course you need to generate JSON based dictionary from language file from php

var my_dictionary = { 
    "some text"  : "a translation",
    "some more text"  : "another translation"
}
$.i18n.setDictionary(my_dictionary);


$('div#example').text($.i18n._('some text'));
过气美图社 2024-08-30 19:40:19

JSGettext (存档链接)是 GNU gettext 规范的最佳实现。
首先下载 JSGETTEXT 包并包含在您的页面中
/js/Gettext.js

<?php
$locale = "ja_JP.utf8";
if(isSet($_GET["locale"]))$locale = $_GET["locale"];
?>
<html>
<head>
<link rel="gettext" type="application/x-po" href="/locale/<?php echo $locale ?>/LC_MESSAGES/messages.po" />
<script type="text/javascript" src="/js/Gettext.js"></script>
<script type="text/javascript" src="/js/test.js"></script>
</head>
<body>
Test!
</body>
</html>

javascript 代码示例

window.onload = function init(){
var gt = new Gettext({ 'domain' : 'messages' });
alert(gt.gettext('Hello world'));
}

作为参考,请查找以下链接。它工作正常,无需将 .js 文件转换为 .php。

点击此处

JSGettext (archived link) is best implementation of GNU gettext spec.
First download JSGETTEXT package and include in your page
/js/Gettext.js

<?php
$locale = "ja_JP.utf8";
if(isSet($_GET["locale"]))$locale = $_GET["locale"];
?>
<html>
<head>
<link rel="gettext" type="application/x-po" href="/locale/<?php echo $locale ?>/LC_MESSAGES/messages.po" />
<script type="text/javascript" src="/js/Gettext.js"></script>
<script type="text/javascript" src="/js/test.js"></script>
</head>
<body>
Test!
</body>
</html>

javascript code for example

window.onload = function init(){
var gt = new Gettext({ 'domain' : 'messages' });
alert(gt.gettext('Hello world'));
}

For reference find below link. It's working fine without converting .js file to .php.

Click here

画尸师 2024-08-30 19:40:19

如果您改掉在代码中使用字符串文字的坏习惯,您的生活就会变得更加轻松。也就是说,不要

 alert("Some message")

使用

alert($("#some_message_id").text())

“#some_message_id”是服务器端生成的隐藏 div 或 span。

You can make your life much easier if you get rid of bad habit to use string literals in your code. That is, instead of

 alert("Some message")

use

alert($("#some_message_id").text())

where "#some_message_id" is a hidden div or span generated on the server side.

客…行舟 2024-08-30 19:40:19

作为进一步的提示,有一个名为 po2json 的 Perl 脚本,它将从 .po 文件生成 json。

As a further hint there's a perl script called po2json which will generate json from a .po file.

我做我的改变 2024-08-30 19:40:19

对于 GNU gettext API 的 JavaScript 实现,这些链接也很有用:
http://tnga.github.io/lib.ijs
http://tnga.github.io/lib.ijs/docs/iJS .Gettext.html

//set the locale in which the messages will be translated
iJS.i18n.setlocale("fr_FR.utf8") ;
//add domain where to find messages data. can also be in .json or .mo
iJS.i18n.bindtextdomain("domain_po", "./path_to_locale", "po") ;
//Always do this after a `setlocale` or a `bindtextdomain` call.
iJS.i18n.try_load_lang() ; //will load and parse messages data from the setting catalog.
//now print your messages
alert( iJS.i18n.gettext("messages to be translated") ) ;
//or use the common way to print your messages
alert( iJS._("another way to get translated messages") ) ;

For JavaScript implementation of GNU gettext API these links can be also useful:
http://tnga.github.io/lib.ijs
http://tnga.github.io/lib.ijs/docs/iJS.Gettext.html

//set the locale in which the messages will be translated
iJS.i18n.setlocale("fr_FR.utf8") ;
//add domain where to find messages data. can also be in .json or .mo
iJS.i18n.bindtextdomain("domain_po", "./path_to_locale", "po") ;
//Always do this after a `setlocale` or a `bindtextdomain` call.
iJS.i18n.try_load_lang() ; //will load and parse messages data from the setting catalog.
//now print your messages
alert( iJS.i18n.gettext("messages to be translated") ) ;
//or use the common way to print your messages
alert( iJS._("another way to get translated messages") ) ;
夜灵血窟げ 2024-08-30 19:40:19

这个库似乎是 JavaScript 中 getText 的最佳实现:

http://messageformat.github.io/Jed/

https://github.com/messageformat/Jed

文档中的示例:

<script src="jed.js"></script>
<script>
var i18n = new Jed({
  // Generally output by a .po file conversion
  locale_data : {
    "messages" : {
      "" : {
        "domain" : "messages",
        "lang"   : "en",
        "plural_forms" : "nplurals=2; plural=(n != 1);"
      },
      "some key" : [ "some value"]
    }
  },
  "domain" : "messages"
});

alert( i18n.gettext( "some key" ) ); // alerts "some value"
</script>

This library seems the best implementation of getText in javascript:

http://messageformat.github.io/Jed/

https://github.com/messageformat/Jed

example from the documentation:

<script src="jed.js"></script>
<script>
var i18n = new Jed({
  // Generally output by a .po file conversion
  locale_data : {
    "messages" : {
      "" : {
        "domain" : "messages",
        "lang"   : "en",
        "plural_forms" : "nplurals=2; plural=(n != 1);"
      },
      "some key" : [ "some value"]
    }
  },
  "domain" : "messages"
});

alert( i18n.gettext( "some key" ) ); // alerts "some value"
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文