JavaScript, Thymeleaf, and localizing text

Our web page is built using a lot of JavaScript. I am having problems replacing text in the generated markup with localized text. JavaScript is not embedded in the webpage, but contains a directive. JavaScript has something like the following:

$("#Dynamic-Modal-Content").empty();     
$("#Dynamic-Modal-Content").append("<div class='dynamic_model' id='dynamic_id'>"+
    "<p>Done?</p></div>");

      

Inside the web page is

<div id="Dynamic-Modal-Content"></div>

      

I need to replace "Done?" with localized text but can't figure out how to do it. I tried the suggestion http://blog.florentlim.com/how-to-write-javascript-including-thymeleaf/#comment-7224 but it didn't work.

This is a simplified version of the real code, but makes sense to the problem.

Any pointers from people in the big, wide world?

0


source to share


1 answer


There are 2 workarounds for this:

  • You can use additional js files with texts for each locale and select the appropriate javascript upon request. Some ui widget libraries take this approach to some extent. However, it has two main disadvantages. Javascript afaik can only resolve locale in the browser, so you still need some kind of communication protocol - with the server if you keep the locale preference in the session. Second, and more importantly, you cannot avoid splitting your i18n texts in different places for each locale - for server and for js.

  • Use html5 data attributes. I believe using html5 data attributes is the cleanest way to transfer data between servers and js, not just i18n.

For example, your div would be:



<div id="Dynamic-Modal-Content" th:attr="data-txt=#{label.done}"></div>

      

then with jQuery you can easily get all the html5 data attributes as if they were jQuery data:

$("#Dynamic-Modal-Content").data("txt");

      

0


source







All Articles