Pergunta

Eu estou usando gettext no meu código PHP, mas eu tenho um grande problema. Todos os meus arquivos JavaScript não são afetados pela tradução, alguém pode me dizer uma maneira fácil de obter as traduções na língua escolhida em JavaScript também.

Foi útil?

Solução

A maneira mais fácil é ter uma gravação de arquivo PHP as traduções de gettext em variáveis ??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"); ?>"

e, em seguida, incluí-lo:

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

Eu também recomendo este método em conjunto com a tradução plugins S. Marcos menciona (que são muito interessantes!).

Você pode definir o dicionário no cabeçalho da página atual, também, sem incluir um arquivo externo, mas dessa maneira, você teria que olhar para cima e enviar os dados em cada carregamento de página - bastante desnecessários, como um dicionário tende a mudança muito raramente.

Outras dicas

Eu geralmente exportar as traduções em uma estrutura de JavaScript:

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

O idioma atual dos textos página pode ser definida usando: <html xml:lang="en" lang="nl">

Isto pode ser lido em JavaScript:

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

E, em seguida, você pode escrever código como este:

alert( app.lang.hello );

Opcionalmente, uma função i18n() ou gettext() pode trazer alguma inteligência, para retornar o texto padrão se a chave não existe). Por exemplo:

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

Tente, jQuery i18n ou jQuery localização

Um exemplo para jQuery i18n, e, claro, você precisa gerar dicionário baseado JSON de arquivo de linguagem de php

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


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

JSGettext ( arquivado ligação ) é melhor implementação de GNU gettext spec. pacote de download JSGETTEXT primeiro e incluem em sua página /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>

código javascript por exemplo

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

Para achado referência abaixo link. É bom trabalhar sem converter arquivo .js para .php.

Clique aqui

Você pode tornar sua vida muito mais fácil se você se livrar do mau hábito de strings literais uso em seu código. Ou seja, em vez de

 alert("Some message")

uso

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

onde "#some_message_id" é um div oculto ou espaço gerado no lado do servidor.

Como mais uma dica há um script perl chamado po2json que irá gerar JSON de um arquivo .po.

Para a implementação JavaScript do GNU gettext API estas ligações também pode ser útil:
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") ) ;

Esta biblioteca parece ser a melhor implementação de getText em javascript:

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

https://github.com/messageformat/Jed

exemplo da documentação:

<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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top