CodeIgniter: Parse dynamic language captions located in javascript

前端 未结 3 1780
囚心锁ツ
囚心锁ツ 2021-01-06 18:21

I have a javascript code that needs localisation, ie.

function js_proc() {
    var some_data = \'this text needs to be translated dynamically at runtime\';
}         


        
相关标签:
3条回答
  • 2021-01-06 18:53

    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.

    0 讨论(0)
  • 2021-01-06 18:56

    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.

    0 讨论(0)
  • 2021-01-06 19:04

    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']
    
    0 讨论(0)
提交回复
热议问题