How to handle localization in JavaScript files?

前端 未结 3 1714
感情败类
感情败类 2020-12-15 23:43

I want JavaScript code to be separated from views.
I got the requirement to implement localization for a simple image button generated by JavaScript:

<         


        
相关标签:
3条回答
  • 2020-12-15 23:51

    Actually ASP.NET Ajax has a built-in localization mechanism: Understanding ASP.NET AJAX Localization

    0 讨论(0)
  • 2020-12-16 00:12

    If you insist on keeping it separate, you could do something like:

    //keep all of your localised vars somewhere
    var title = '{title_from_server}';
    document.getElementById('someImage').title = title;
    

    Remember, if you use JavaScript code to initialize any text of elements, your site will degrade horribly where JavaScript isn't available.

    0 讨论(0)
  • 2020-12-16 00:14

    EDIT

    Consider writing the necessary localized resources to a JavaScript object (hash) and then using it for lookup for your dynamically created objects. I think this is better than going back to the server for translations. This is similar to adding it via viewdata, but may be a little more flexible. FWIW, I could consider the localization resources to be part of the View, not part of the controller.

    In the View:

    <script type="text/javascript"
             src='<%= Url.Content( "~/Resources/Load?translate=Close,Open" %>'></script>
    

    which would output something like:

    var local = {};
    local.Close = "Close";
    local.Open = "Open";
    

    Without arguments it would output the entire translation hash. Using arguments gives you the ability to customize it per view.

    You would then use it in your JavaScript files like:

     $(function(){
         $('#button').click( function() {
            $("<img src=... title='" + local.Close + "' />")
               .appendTo("#someDiv")
               .click( function() { ... } );
         });
     });
    

    Actually, I'm not too fussed about keeping my JavaScript code out of my views as long as the JavaScript code is localized in a container. Typically I'll set my master page up with 4 content area: title, header, main, and scripts. Title, header, and main go where you would expect and the scripts area goes at the bottom of the body.

    I put all my JavaScript includes, including any for viewusercontrols, into the scripts container. View-specific JavaScript code comes after the includes. I refactor shared code back to scripts as needed. I've thought about using a controller method to collate script includes, that is, include multiple scripts using a single request, but haven't gotten around to that, yet.

    This has the advantage of keeping the JavaScript code separate for readability, but also allows me to easily inject model or view data into the JavaScript code as needed.

    0 讨论(0)
提交回复
热议问题