4

I have been calling my javascript function from Thymeleaf as below:

th:onclick="'viewDocument(\'' + ${document.docTypeLongDesc} +'\');'"

But I just updated my spring boot version to 2.1.4 RELEASE with which Thymeleaf also got updated. And the previous version in no longer supported.

On further research I found out that I should be able to use

th:onclick="' viewDocument (this.getAttribute ('document.docTypeLongDesc'));'"

However, it doesn't give any error but neither does it work. I have removed the argument and was able to call the function just fine. So I am guessing I am not passing the argument right way. Any guidance will be helpful. TIA.

2 Answers 2

3

See this: Restricted mode: Avoid variable expressions returning strings in processors for event handlers (th:on*).

In order to correctly pass Thymeleaf variables to the onclick event, put the variable in a data attribute, and read it using getAttribute().

th:data-longDescription="${document.docTypeLongDesc}" onclick="viewDocument(this.getAttribute('data-longDescription'));"
Sign up to request clarification or add additional context in comments.

3 Comments

I referred the same link and use it the same way but still getting the runtime error: org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "templates/th_documentsDetails.html") . Also Intellij highlight this.getAttribute as red and on highlighting says can't recognize. I am thinking it's most likely a syntax error somewhere.
@ILRNew Did you notice that I'm no longer using th:onclick, now it's just a regular onclick as it no longer needs to be a thymeleaf expression.
You are actually right. I didn't notice that. Once I did that it work like a charm. thank you very much. Can I ask you on how to learn more about new Thymeleaf?
-2

You should use it as follows:

th:onclick="${'viewDocument(' + document.docTypeLongDesc + ');'}"

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.