0

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?

4
  • Can you please add the coresponding controller-snippet to the question? Commented Aug 24, 2018 at 14:10
  • 1
    If variable is null, it means Thymeleaf is doing it's job (replacing /*[[${variable}]]*/ 'value' with the contents of ${variable}) but that you likely haven't added ${variable} to the model. You have a misspelling, or you really are setting ${variable} to null. Commented Aug 24, 2018 at 14:53
  • @Metroids Oh, I have to add variable to the model in controller? I am pretty sure that I didn't do that. I'll give it a try later since I don't have the access to project from home. Thanks. Commented Aug 24, 2018 at 15:05
  • @Metroids That was it, if you want to, post an answer. Thanks again. Commented Aug 27, 2018 at 17:26

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.