简体   繁体   中英

A way to translate JS with Poedit

I´m translating strings in PHP with Gettext and Poedit software. I would like to use translated strings also in JavaScript, but without putting the code inline into HTML-documents, but in external files. Inline in HTML-documents it would be no problem because the inline JS-code is also rendered. An example:

var hello = <?=_("hello");?>

The translator should use the same translation-tables as the php-code does (because of duplicate strings).

So my idea was to "compile" the JavaScript files with PHP. For example in an external JS-file is this code:

if (window.confirm("_translate('are_you_sure')")) {
location.href = this.href;
}

A php script reads this code above and finds all strings inside _translate() . The code will replace _translate('are_you_sure') with the translated string. It works but is never translating, because the Poedit software will not find the string in _translate() even if I add _translate into the keys of the source. So there is no translated strings to be translated.

So my question is how to tell Poedit that he should read strings with _translate() inside a javascript-file?

you could include a php script, which do the translations in the javascript file

$js = $_GET['js'];

// security check
if (preg_match('~[^a-z0-9_-]~', $js)) {
    die("invalid js");
}

$content = file_get_contents('path_to_js/' . $js . '.js');
preg_match_all('~_translate\(\'([^\']+)\'\)~', $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $content = str_replace($match[0], _($match[1]), $content);
}
echo $content;

so you have to include instead of yourscript.js the php file script.php?js=yourscript

So my question is how to tell Poedit that he should read strings with _translate() inside a javascript-file?

Add the _translate keyword (which is a non-default one for JS) to the keywords list and add the path to your .js file. That's it. Poedit/xgettext supports JavaScript for quite some time now.

You misdiagnosed your problem, though, and Poedit's JS support isn't it. The real problem is that you're expecting Poedit/xgettext to parse a string literal that happens to contain some code. "_translate('are_you_sure')" is not JavaScript code (that xgettext could find the _translate function in) in your example above — it's a string! And you're asking the confirm() function to display it including the "_translate" bit, it makes no sense.

You wouldn't have that problem with code like this:

msg = _translate('are_you_sure');
if (window.confirm(msg)) {
  location.href = this.href;
}

(Of course, you have to ensure client-side JS gettext deployment, including access to MO files, then, which is more work then translating strings on the PHP side.)

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