4

I use Thymeleaf with Spring MVC 4.1.1 and I want to be able to re-use my Spring messages (with the user's automatically detected locale) for my JavaScript files. E.g. I want to do:

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

...and #fooTitle would contain the value under foo.title for the user locale.

What would be the easiest way to do this? Note that I would like a JavaScript object ("dictionary") or another data structure which is easy to navigate.

2 Answers 2

2

If not the easiest (but admittedly easy enough), the cleanest and most robust way is to use html5 data attributes to pass back-end data to js. This way, no matter if you move your javascript to external files, it still works. Use some element as container (choose the most proper for your case) as a carrier of the thymeleaf back-end retrieved i18n 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 has not left any sign of life after that :) ) , JavaScript, Thymeleaf and localizing text

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that is indeed clever and would work, but in my particular case, it's simply not manageable!
0

The easiest way to include localization messages would be:

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

1 Comment

Thank you, but in this case, the JavaScript files are all split up and I'd just like to be able to access a JavaScript object ("dictionary") with all the messages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.