Javascript translate text strings

Permalink
What is the best practice regarding translation of javascript string on the front-end?

I use the getJavaScriptStrings and included the ccm_app/ui.js, but string won't translate properly.

Any help would be appreciated!

A3020
 
mkly replied on at Permalink Reply
mkly
Hello,
getJavascriptStrings will help you out in the backend but for front end, common practice is to create a tools file and include in the front end.

Like a file
/tools/site_translation_strings_js.php

In that file
<?php
defined('C5_EXECUTE') or die("Access Denied.");
header('Content-type: text/javascript');
?>
var siteTranStrings = {
  pizzaTime : "<?= t('Pizza Time') ?>",
  panda     : "<?= t('Panda') ?>"
}


Then include that tools file as you would include a javascript file with addHeaderItem() or addFooterItem and use it in js like
$('#my-header-text').text(siteTranStrings.pizzaTime);



Best Wishes,
Mike
A3020 replied on at Permalink Reply
A3020
Hi Mkly, thanks for your reply. It looks like a workable solution.

How would you pass strings from the controller to the tools file?
jshannon replied on at Permalink Reply
jshannon
How are you going from a controller to a tool? That's... atypical.

If you mean controller to view, then you pass them variables (or variable as in my example) as you do anything else:

$this->set('strings', $strings);
jshannon replied on at Permalink Best Answer Reply
jshannon
FYI:

When I do things like this, I create a PHP array then json_encode() it, so:

<? $strings = array('pizzaTime' = t('Whatever')) ?>
var siteTranStrings = <?= json_encode($strings) ?>;


Building it in PHP is arguably easier and less error prone, and json_encode will handle any necessary quoting. Additionally, it's relatively easy to add strings to the array bit-by-bit, or to create the array as part of a loop ( foreach($keys) { $strings[$key] = t($key); } ). Also, the output is a bit more efficient.
A3020 replied on at Permalink Reply
A3020
Ok, that will work. Thanks!

//view
<script language="javascript">
   var translateStrings = JSON.parse('<?= $translateStrings ?>');
   alert(translateStrings.dateFormat);
</script>


//controller
public function view() {
   $string = array(
      'dateFormat' => 'dd MM yy'
   );
   $this->set('translateStrings', json_encode($string));
}