Sometimes it is necessary to transfer some variables from properties to a javascript file. When the js code is connected inline, there is no problem transferring the desired variable using thymeleaf. How can I transfer a certain variable from properties to js file? Thank you in advance!

At the moment I have 2 solutions: 1) Create @ControllerAdvice and add @ModelAttribute, and in the method return Map. Print it into thymeleaf using th: each. And then the script get the data attribute of the desired tag. 2) Create an @RestController with a GET method that returns a Map when it is accessed. And then the script makes an AYAX request to the URL and gets the necessary parameters.

  • 2
    Firstly, Thymeleaf can be configured to handle js files. Secondly, it is possible to insert data into the page, and in the code from the connected js-files to use this data. Third, you can write an additional endpoint on the backend, which will give the data in response to a request from the front. - Sergey Gornostaev
  • Hello! In principle, the first option is true for inline scripts. And I have already implemented the second and third options. I thought, maybe there is some other option that would give such an opportunity. Thanks for the answer! - Orkhan Hasanli

1 answer 1

I thank everyone who helped to resolve this issue. The following option came up for me: 1) Created @ControllerAdvice , which passed @ModelAttribute to all templates

A simple example:

 @ControllerAdvice public class GlobalControllerAdvice { @Value("${base.url}") private String baseUrl; // Получить нужные переменные из properties @ModelAttribute("baseUrl") public String getBaseUrl() { return baseUrl; } } 

Next, the following code is inserted into the head. (In this example I use Thymeleaf)

 <script th:inline="javascript"> /*<![CDATA[*/ var baseUrl = [[${baseUrl}]]; /*]]>*/ </script> 

After that, this variable is available in the document and can be safely used both in inline scripts and in plug-in scripts.

Other options for implementation: Create a controller and GET method, which when accessing the url will return JSON (Map). And then the script sends an AYAX request to the URL and parses the result.

Another option is if the script is inline and you use the thymeleaf template engine, you can safely use variables in inline scripts.