Gavrilo Adamovic
Gavrilo Adamovic

Reputation: 2795

Setting thymeleaf variable using th:inline always sets the variable to null

I want to make a javascript variable that I can use with th:if in thymeleaf.

What I did:

<script th:inline="javascript">
/*<![CDATA[*/

    var variable = /*[[${variable}]]*/ 'value';
    console.log(variable); //prints 'null'

/*]]>*/
</script>

When I check the page source this is how the page is rendered:

<script>
/*<![CDATA[*/

    var variable = null;
    console.log(variable);

/*]]>*/
</script>

Why variable is constantly being set to null?

Upvotes: 0

Views: 536

Answers (1)

Metroids
Metroids

Reputation: 20477

If you're getting var variable = null; in the source, that means Thymeleaf is doing it's job -- replacing /*[[${variable}]]*/ 'value' with the contents of ${variable}. Since it's null, you:

  1. Haven't added ${variable} to the model.
  2. Misspelled variable somewhere.
  3. Added ${variable} to the model as null.

Upvotes: 1

Related Questions