Skip to content
JoshuaChi edited this page Sep 13, 2010 · 2 revisions

A simple javascript i18n helper that I used in my site(5span.com) with CakePHP framework.
1.
Firstly you should set your language files in locale folder.
app-
-——locale-
-———————en_us-
-———————————-lang.php
-———————zh_cn-
-———————————-lang.php

The en_us/lang.php file will looks like:
[CODE]
<?php
$lang = array(
‘LBL_DEMO_MESSAGE’ => ‘Demo Message’,
);

[/CODE]

The ZH_CN/lang.php file will looks like:
[CODE]
<?php
$lang = array(
‘LBL_DEMO_MESSAGE’ => ‘测试数据’,
);

[/CODE]

2.
Secondly, add jsi18n helper into your controller.
[CODE]
var $helpers = array(‘jsi18n’);
[/CODE]

3.
Thirdly, you can link this jsi18n file in your layout. Like this:
[CODE]
<?php
echo $jsi18n→link(‘jsi18n.js’);
?>
[/CODE]
It will generate the jsi18n.js cache file under app\tmp\cache\jsi18n\.

4.
At last you can use it in your javascript file.
Add a function to translate the message string. Change the function as you like, this is just a simple example.
[CODE]
function __t(key){
if(GLOBAL_LANGUAGE == CN){
return zh_cn_lang[key];
}
else{
return en_us_lang[key];
}
}
[/CODE]

[CODE]
jQuery.validator.addMethod(“alphanumeric”, function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, __t(“LBL_JQUERY_ALPHANNUMERIC_ERROR”));
[/CODE]

There are still a lot of work you should do in helpers/jsi18n.php. Notice this line
[CODE]
var $langs = array(‘en_us’,‘zh_cn’);
[/CODE]

You should replace the item in this array with the folder name under app/locale.

Clone this wiki locally