0

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?

1

2 Answers 2

1

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.

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

Comments

1

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.

Comments

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.