How to put thymeleaf code in external javascript file?

I have an external javascript file that is declared in my html file with the following tag:

<script type="text/javascript" th:inline="javascript" th:src="@{/js/gp-aprobarDocumento.js}"></script> 

and in gp-aprobarDocumento.js the code below:

 ventanaAprobacion = function(td) { /*<![CDATA[*/ idEntregable = $(td).attr("data-row-id"); idVersion = $(td).attr("data-row-version"); alert("la siguiente viene con el texto dle properties"); alert(/*[[${link.menu.page-certificacion-qa-bandeja-entrada}]]*/); $(function() { $("#dialog-aprobar-documento").dialog("open"); }); /*]]>*/ } 

Thus, when the function is executed, the window warning is displayed blank.

Does anyone know how to put a thimeleaf expression in external javascript?

+11
source share
2 answers

I think that you want to do this is not possible, I have a similar question (here: How to access the model attribute with javascript variable )

but in your case you can do something like this:

in html:

 <script type="text/javascript" th:inline="javascript" > var alertVariable = ${link.menu.page-certificacion-qa-bandeja-entrada}; </script> 

and in javascript:

 ventanaAprobacion = function(td) { ... alert(alertVariable); ... } 

I know that it’s not really what you want, but I have the same problem and I don’t think there is any solution.

+8
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 & lt;> and added this object to the DOM via Spring Controller.

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

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

  th:text="${myResult}" 

You can also reference it in your Javascript by simply referring to the model object name from the DOM. I could not get the variable to populate in a separate JS file without making it global in volume from the HTML file with:

 <script th:inline="javascript"> var myResult = [[${myResult}]]; </script> 

My JS file is as follows

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

Return result from DOM

This 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. It seems like thymeleaf 3 has other solutions too: https://github.com/thymeleaf/thymeleaf/issues/395

Hope this helps!

+1
source

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


All Articles