CakePHP does not have a built-in / standard way to localize JavaScript. It offers various ways to localize strings in general. See Internationalization and Localization.
To localize strings output using JavaScript, consider:
For βstaticβ lines (that is, lines that are independent of the content of your site), create localization files for your scripts. Many plugins use this approach. For example, see this page on localizing date pickers. JQuery-UI UI / Datepicker / Localization
If you already localize strings on your website via .po files and want to use the same translations in your JavaScript, you might consider dynamically creating translation files, as indicated in 1.) , for example
In your app/Config/routes.php , enable parsextensions, see File Extensions
Router::parseExtensions('json');
Create a controller that will output strings localized as JavaScript / JSON
http://example.com/localized/strings/eng.json class LocalizedController extends AppController { public function strings($lang) { if('json' !== $this->request->ext) { throw new NotFoundException(); } // Switch to the requested language Configure::write('Config.language', $lang); $strings = array( 'hello', 'world', ); //translated the strings $translations = array(); foreach ($strings as $string) { $translations[$string] = __($string); } // build and send a JSON response $this->autoRender = false; $this->response->type('json'); $this->response->body(json_encode($translations)); return $this->response; } }
This json file should now be accessible through http://example.com/localized/strings/eng.json and can be loaded from your javascripts at runtime
note
Just clarify; the example is untested and simply illustrates the idea of ββdynamically creating JSON (or JavaScript) files containing localized strings. The code is far from efficient and (at least part) the code should not be inside the controller, but (for example) inside the model.
source share