Spring messaging in JavaScript and Thymeleaf

I am using Thymeleaf with Spring MVC 4.1.1 and I want to be able to reuse my Spring messages (with auto-defined locale) for my JavaScript files. For example. I want to do:

$('#fooTitle').text(messages['foo.title']);

      

... and #fooTitle will contain the pod value foo.title

for the custom locale.

What's the easiest way to do this? Note that I need a JavaScript object ("dictionary") or some other data structure that is easy to target.

+3


source to share


2 answers


If not the simplest (but admittedly simple enough), the cleanest and most reliable way is to use html5 data attributes to pass back-end data to js. This way, no matter you move your javascript to external files, it still works. Use some element as a container (choose the one that best suits your case) as a carrier for thymeleaf i18n return values ​​and then access them with jQuery

in html:

<div id="container" th:attr="data-foo-title-txt=#{foo.title}"></div>

      



in js:

$('#fooTitle').text($("#container").data("foo-title-txt"));

      

See also my older similar answer (although the OP didn't leave any signs of life after that :)), JavaScript, Thymeleaf and localized text

0


source


The easiest way to enable localization messages is:



$('#fooTitle').text([[#{foo.title}]])

      

-1


source







All Articles