How to access model attribute with javascript variable

I add an attribute to my ModelAndView in spring and then forward it to my thymeleaf view.

In the view, I have the following code:

 <script th:inline="javascript"> /*<![CDATA[*/ var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test"; var collectedValueJson = [[${collectedValues}]]; console.log(collectedUserJson); /*]]>*/ </script> 

The result of this is

 var applicationName = 'collectedValues'; var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]'; 

It's good. Now my desire is that I can take the var application and get the modelattribute attribute with this variable, but this does not work.

Result:

 var tmp2 = ${applicationName}; 

Another attempt was that I have access to the model attribute with the syntax /*[[ ]]*/ on the first try:

 var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/}; 

But the result will be:

 var tmp = ${'collectedValues' 

I have no idea what I can try.

Any other suggestions?

Thanks in advance.

+2
source share
4 answers

you cannot access the attributes of the model, therefore, they are on the server side and they get lost when rendering jsp in HTML

+3
source

There is a workaround worth mentioning: write attribute

 <span id="myvar" th:text="${attributeName}"></span> 

and then read it using javascript using

 document.getElementById("myvar").value 

or some other jQuery call:

 $('#myvar').text() 

It is inelegant, but it works.

+2
source

You can:

 <span id="span_id" style="display: none;" th:text="${attributeName}"></span> 

and then in your Javascript:

 document.getElementById("span_id").innerHTML 
0
source

Via the DOM:

https://datatables.net/examples/data_sources/js_array.html

If you want to create a JS variable from a Thymeleaf object, you can add the specified object to the DOM. I recently completed a project in which I returned the results of a query to a Java object of type List <> and added this object to the DOM via Spring Controller.

  //Deliver Results Array to the DOM model.addAttribute("myResult", myResult); 

After this object is added to your Thymleaf template model, you can access it in your HTML as

  th:text="${myResult}" 

You can also reference it in your Javascript just by referencing the model object name

  $(function(){ //Get Thymeleaf DOM Object console.log(myResult); }); 

Return result from DOM

But the object must be referenced from within the DOM. You may have better performance with AJAX and creating a controller that returns data to the client via HTTP.

Hope this helps!

0
source

Source: https://habr.com/ru/post/978803/


All Articles