Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to internationalize string used in javascript code?

While developing AJAX program, I met the design decision to make string I18N in JavaScript.code. Some string is only used by JavaScript. For example.

$('#submit').click(function() {
    $(#target).html('Please wait while submitting...').load(someURI);
}

I'd like to I18N the string 'Please wait while submitting...'. I'm not sure what's the best way to do it. Currently, I just have the string I18N-ed in server and rendered into a javascript variable in page (I'm using PHP/wordpress).

<script>strSubmit = <?php  _e('Please wait while submitting...'); ?></script>

Then, in javascript, I just use the varialble

$('#submit').click(function() {
    $(#target).html(strSubmit).load(someURI);
}

This works, but it looks messy. Is there any better way to achieve this?

like image 795
Morgan Cheng Avatar asked Oct 12 '09 09:10

Morgan Cheng


2 Answers

You should use JSON to convert the server side l10n strings to a JSON object :

// In the <head> tag :
<script type="text/javascript" src="locales.php"></script> 

and this in locales.php :

var l10n = <?php echo json_encode($l10n); ?>;

where $l10n is an array which contains all the locales, like this :

$l10n = array(
  'Please wait while submitting...' => 'Veuillez patienter durant le traitement...',
  'bah' => 'bih'
);

You can now use these strings like this in JS :

function $T(s){
  return l10n[s] || s;
}

alert($T('Please wait while submitting...'));
like image 130
Fabien Ménager Avatar answered Sep 30 '22 07:09

Fabien Ménager


you can also automate this by using a php "preprocessor" for javascript

<script src="script.php?file=blah.js">

where script.php is something like

    function _repl($x) { return '"' . _e($x[1]) . '"'; }

    $js = file_get_contents($_GET['file']);
    $js = preg_replace_callback('~_e\("(.+?)"\)~', '_repl', $js);
    echo $js;

this will transparently replace _e(something) in javascript code with actual strings

like image 31
user187291 Avatar answered Sep 30 '22 09:09

user187291