Variable expression into javascript without using th:inline

前端 未结 6 960
广开言路
广开言路 2020-12-10 04:41

I searched first but I found confusing answers since I\'m new to Thymeleaf and amateurish at best at javascript.

I just want to know how to pass variable expressions

相关标签:
6条回答
  • 2020-12-10 05:17

    This one worked:

    th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"
    

    Thanks goes out to the thymeleaf forum: http://forum.thymeleaf.org/variable-expression-into-javascript-without-using-th-inline-td4025534.html

    0 讨论(0)
  • 2020-12-10 05:17

    In Thymeleaf version 2.1, I have not been able to get the accepted answer to work. I did find some guidance from a Twitter post from Thymeleaf. Rather than using th:onclick, you use th:attr and specify the onclick attribute therein.

    th:attr="onclick='javascript:getContactId(\'' + ${contact.id} + '\');'"
    
    0 讨论(0)
  • 2020-12-10 05:18

    You can do this like:

    th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'"

    0 讨论(0)
  • 2020-12-10 05:21

    I have asked the Thymeleaf project on twitter, and their answer is:

    You can use both the "+" operator or literal substitutions. For example: <a th:href="|javascript:change('start','${taskId}')|">

    For more info: https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

    I have tried, and it works~

    0 讨论(0)
  • 2020-12-10 05:22

    You can not put javascript variables into onclick or other DOM attributes. The value of onclick or any other DOM attribute should be a constant string.

    However, you can dynamically modify value of onclick attribute from javascript, like this:

    yourDomElement.onclick = anyVariable;
    
    0 讨论(0)
  • 2020-12-10 05:36

    A more generic approach, if you need in JS something that isn't passed as a event handler parameter:

    th:attr="data-myValueFromThymeleaf=${contact.id}"

    Any attribute whose name is starting with data- is ignored by all browsers. So it won't affect the UI and you can easily read the value in javascript.

    I prefer this because it's not ideal to put javascript code in html (see unobtrusive javascript)

    0 讨论(0)
提交回复
热议问题