I have a javascript code that needs localisation, ie.
function js_proc() {
var some_data = 'this text needs to be translated dynamically at runtime';
}
So I re-wrote like this:
function js_proc() {
var some_data = <?php echo $this->lang->line('some_data_id'); ?>;
}
In the view, I wrote the js link like this:
<script type="text/javascript" src="www.domain.com/codeigniter/get_js/file-1/"></script>
which calls the function get_js() in the controller. The idea is to have the get_js() function read the js file(s) and translate the language strings...
There are way too many js strings to be translated, so I can't pass every string
as a variable. Ideally I'd like to make this work through the codeigniter language files.
My question is: is there a way to parse the php parts in the js file & executed (=translate) them? ie.
class App extends CI_Controller
{
function get_js {
$content = file_get_contents($js_file);
echo parse_php($content);
}
...
}
Thanks!
Depending on how big the language file is, a quick way to allow javascript to access your entire language array could be to load the array into a global javascript array;
<script>
var globalLang = <?php echo json_encode($this->lang->language); ?>;
</script>
Then access in your javascript like this;
globalLang['some_lang_key']
I'm not quite sure what you mean by "There are way too many js strings to be translated, so I can't pass every string as a variable", but if you are looking for some automatic parsing, this won't help.
But this may help others, so here goes.
For from ideal, I use a system like the following:
In my view, I add the localizations as JavaScript global variables, using the codeigniter languages support. Something like:
<script type="text/javascript">
var noEmailError = "<?php echo $this->lang->line('enter_your_email'); ?>";
</script>
Then after that, usually,right after, I include the scripts that refernce the globals:
<script type="text/javascript" src="/scripts/validate.js"></script>
inside the script:
alert(noEmailError);
will show the localized text just fine.
Create a json object in the global scope of the page output for your javascript strings:
<script>
var oGlobalStrings = {
some_data : '<?=$this->lang->line('some_data_language_key');?>'
}
</script>
Then you can use it throughout your Javascript app using the syntax:
oGlobalStrings.some_data
Works very well and can be handled very easily throughout your app.