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!
I use the getJavaScriptStrings and included the ccm_app/ui.js, but string won't translate properly.
Any help would be appreciated!
Hi Mkly, thanks for your reply. It looks like a workable solution.
How would you pass strings from the controller to the tools file?
How would you pass strings from the controller to the tools file?
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:
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);
FYI:
When I do things like this, I create a PHP array then json_encode() it, so:
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.
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.
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)); }
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
Then include that tools file as you would include a javascript file with addHeaderItem() or addFooterItem and use it in js like
Best Wishes,
Mike