문제

나는 사용 중입니다 gettext 내 PHP 코드에서는 큰 문제가 있습니다. 내 모든 JavaScript 파일은 번역의 영향을받지 않습니다. 누군가가 선택한 언어로 번역을 JavaScript로 쉽게 얻을 수있는 방법을 말해 줄 수 있습니다.

도움이 되었습니까?

해결책

가장 쉬운 방법은 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 언급 (매우 흥미 롭습니다)과 함께 권장합니다.

외부 파일을 포함하지 않고 현재 페이지 헤더에서 사전을 정의 할 수 있지만, 그러면 사전이 거의 변하지 않기 때문에 모든 페이지로드에서 데이터를 찾아서 보내야합니다.

다른 팁

나는 일반적으로 JavaScript 구조로 번역을 내 보냅니다.

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

페이지 텍스트의 현재 언어는 다음을 사용하여 정의 할 수 있습니다. <html xml:lang="en" lang="nl">

JavaScript로 읽을 수 있습니다.

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

그런 다음 다음과 같은 코드를 쓸 수 있습니다.

alert( app.lang.hello );

선택적으로, a i18n() 또는 gettext() 함수는 키가 존재하지 않으면 기본 텍스트를 반환하기 위해 약간의 지능을 가져올 수 있습니다). 예를 들어:

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

노력하다, jQuery i18n 또는 jQuery 현지화

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'));

jsgetText (보관 된 링크) GNU GetText 사양의 가장 좋은 구현입니다. 먼저 jsgettext 패키지를 다운로드하고 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 코드입니다

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

참조를 위해 아래 링크를 참조하십시오. .js 파일을 .php로 변환하지 않고 잘 작동합니다.

여기를 클릭하십시오

코드에서 문자 그럴을 사용하는 나쁜 습관을 제거하면 인생을 훨씬 쉽게 만들 수 있습니다. 즉, 대신입니다

 alert("Some message")

사용

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

여기서 "#some_message_id"는 서버 측에서 생성 된 숨겨진 분위기 또는 스팬입니다.

추가 힌트로 po2json이라는 Perl 스크립트가있어 .po 파일에서 JSON을 생성합니다.

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") ) ;

이 라이브러리는 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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top