Search code examples
javascriptthymeleaf

Thymeleaf syntax is not working in java script file


I am using spring boot to provide data to thymeleaf.

var list = [(${listStudents})];

listStudents is a list of students with the help of which I populate data in HTML which is working fine but fetching the same list in java script using thymeleaf shows error in the above line as: , expected.

I have added th:inline="javascript" attribute to script tag in HTML file as:

<script th:inline="javascript" src="home_script.js"></script>

Trying to solve this since yesterday. Thanks in advance!


Solution

  • The , expected error is the standard JavaScript syntax error for var list = [(${listStudents})];. To handle this, Thymeleaf supports placing its inline expressions inside JavaScript comments:

    var list = /*[[${listStudents}]]*/ [];
    

    Because the Thymeleaf expression is in a JS comment, note how we have to provide a default (visible) JS value, to keep JavaScript from raising a different syntax error. I used [] because you have a list. You could have used '', or null or whatever is most suitable. Assuming your Thymeleaf is rendered correctly, this extra syntax will be ignored.

    See JavaScript natural templates for details.


    However, I do not think this will completely resolve your problem, unless you have already configured a JavaScript template resolver in your application.

    You are using this:

    <script th:inline="javascript" src="home_script.js"></script>
    

    First of all, the th:inline="javascript" portion has no effect, because your JavaScript code is in an external file: home_script.js (i.e. it is not embedded in your HTML file).

    If you want Thymeleaf to process the Thymeleaf expressions in that separate JS file, you have to tell Thymeleaf to explicitly process external JavaScript files (just like it processes HTML files).

    You probably only have a HTML resolver - and your JS code is not embedded in your HTML file - it is in its own separate JS file. See this demo application which shows how to set up what I think you may need.


    Alternatively you can simply embed your JS directly into the <body> of your HTML file, and don't use an external JS file:

    <body>
    
        <script th:inline="javascript">
            var list = /*[[${listStudents}]]*/ [];
        </script>
    
    </body>
    

    If you still need to use an external JS file, you can assign all your Thymeleaf-generated variables inside your HTML file (like the example above) and then pass these variables as function parameters into the various JavaScript functions in your JS file.

    Using this approach means your JS file does not need to contain any Thymeleaf expressions - it just receives the rendered values from the JS fragment in your HTML file.