JavaScript,Thymeleaf和本地化文本 [英] JavaScript, Thymeleaf and localizing text

查看:571
本文介绍了JavaScript,Thymeleaf和本地化文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的网页是使用 的JavaScript构建的。我无法用本地化文本替换生成的标记中的文本。 JavaScript 不是内嵌到网页,而是带有指令。在JavaScript内部类似如下:

  $(#Dynamic-Modal-Content)。empty(); 
$(#Dynamic-Modal-Content)。append(< div class ='dynamic_model'id ='dynamic_id'>+
< p>完成< p为H.< / DIV>中);

在网页中有一个

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

我需要替换完成?与本地化的文字,但无法弄清楚如何。我尝试了 http://blog.florentlim上的建议.com / how-to-write-javascript-including-thymeleaf /#comment-7224 ,但没有成功。

这是一个简化版本真正的代码,但有问题的要点。



任何指向来自大,宽世界的人?




  • 您可以使用额外的js文件与每个地区的文本,并选择适当的JavaScript的需求。一些ui widget库在某种程度上使用这种方法。但它有两个主要缺点。如果您在会话中保留语言环境首选项,那么Javascript afaik只能从浏览器解析语言环境,因此您仍然需要一些通信参数 - 传递给服务器。其次,更重要的是,你不能避免将你的i18n文本分成不同的位置,每个区域设置一个服务器端和一个js文件。

  • 使用html5数据属性。我相信使用html5数据属性是在服务器端和js之间进行数据通信的最简单方法,不仅适用于i18n。




例如你的div变成:

 < div id =Dynamic-Modal-Contentth:attr =data- TXT =#{label.done}>< / DIV> 

然后使用jQuery,您可以轻松检索所有html5数据属性,就像它们是jQuery数据一样:

  $(#Dynamic-Modal-Content)。data(txt); 


Our web page is built using a lot of JavaScript. I'm having trouble replacing text within generated markup with localized text. The JavaScript is not inline to the web page, but brought in with a directive. Within the JavaScript is something like the following:

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

Within the web page is a

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

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

This is a simplified version of the real code, but has the gist of the problem.

Any pointers from folks out in the big, wide world?

解决方案

There are 2 workarounds for this:

  • You can use additional js files with the texts for each locale and pick the proper one with javascript on demand. Some ui widget libraries use this approach to some degree. However it has two major disadvantages. Javascript afaik can only resolve locale from the browser so you still need some communication -parameter passed- with server, if you keep a locale preference in session. Secondly and more important, you can't avoid splitting your i18n texts in different locations for each locale -one for server side and one for js.

  • Use html5 data attributes. I believe using html5 data attributes is the cleanest way to communicate data between server side and js, not only for i18n.

For example your div becomes :

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

then with jQuery you can retrieve easily all html5 data attributes as if they are jQuery data:

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

这篇关于JavaScript,Thymeleaf和本地化文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆