I need to read model attribute returned from my spring controller and use that value in javascript to alert the value in the UI. I am using thymeleaf.
how do i read the model value and use it in javascript?
I need to read model attribute returned from my spring controller and use that value in javascript to alert the value in the UI. I am using thymeleaf.
how do i read the model value and use it in javascript?
When you return the model from the backend to post alert using javascript. You can do something like this:
Spring Java:
model.put("value", "Test");
Or you can also set @ModelAttribute Annotation.
To assign a value :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${value}]];
/*]]>*/
</script>
Here value is the model name which you pass it from the backend.
The feature you are looking for is called Script inlining.
<script th:inline="javascript">
/*<![CDATA[*/
...
var modelValue = /*[[${model.value}]]*/ 'default value';
...
/*]]>*/
</script>
In this example your model contains an object model
which has a string attribute value
. It is recommended to put the thymeleaf code into JavaScript comments, so there are no errors if you load the page without thymeleaf. If there is an error parsing your thymeleaf expression, the value after the comment is defaulted to.
Apart from String values, it also supports Numbers, Booleans, Arrays, Collections, Maps and Beans.
For further information check out the Documentation.