简体   繁体   中英

Thymeleaf - set resource message from javascript

I'm using thymeleaf. There is no problem with displaying the resource message when the page is first opened. But I am having a problem when I want to re-render the inside of select after ajax request.

Html(first load):

<select onchange="destLangChanged()" class="no-round-input-bg" id="destLang">
    <option value="en" th:utext="#{lang.en}"></option>
    <option value="fr" th:utext="#{lang.fr}"></option>
</select>

Javascript side:

var $el = $("#destLang");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("th:utext", "[[#{lang.en}]]").attr("value", '#{lang.en}'));

As you can see I tried both with two different methods without both "[[# {}]]" and "# {}".

at the end of this code, I am expecting for '#destLang' to be emptied and adding the value of lang.en from resource. but the result is as follows.Option is added but resource message is not displayed properly

在此处输入图像描述

Thanks for your helps.

Extending @connexo's comment.

Lets first think about, what is thymeleaf and how it works. Thymeleaf is a templating language which can bind values (both way, HTML to Java object, Java object to HTML). These templated files are stored in resource folder and whenever client asked for these files, server run these templates with necessary java objects to resolve the final HTML. In the final generated HTML you never see thymeleaf attributes. Browser does not understand these attributes. So thyemleaf attributes are resolved in server side.

So these thymeleaf attributes you are adding is not resolved by server side, that is why, doing so in javascript is not reflecting as it were reflecting while modifying original template files.

Hopes it shed a light upon your question.

Normally, with a default Spring Boot/Thymeleaf application, you can use ..?lang=fr to change the used locale. So instead of trying to do something in JavaScript, you can add something like this:

<a th:href="@{/(lang=en)}">English</a>
<a th:href="@{/(lang=fr)}">Français</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM