Using thymeleaf variable in onclick attribute

2020-05-20 05:10发布

In my current spring-boot project, I have one view with this html code:

<button type="button" class="btn btn-primary" onclick="upload()" th:utext="#{modal.save}"></button>

in the onclick attribute, the call for the function upload() should have one parameter, which value is stored in the thymeleaf variable ${gallery}.

Anyone can tell mehow to use the expression in the above command?

I already try this:

  • th:onclick="upload(${gallery)"

  • th:attr="onclick=upload(${gallery)"

None of this worked.

6条回答
趁早两清
2楼-- · 2020-05-20 05:43

The older replies does not work in the new version of 3.0.10. Now you need:

<button th:data-id="${quartzInfo.id}" 
    onclick="del(this,this.getAttribute('data-id'))" type="button">
</button>
查看更多
Root(大扎)
3楼-- · 2020-05-20 05:44

In 3.0.10 version of Thymeleaf

use [[ ]] it's more easier , thymeleaf goes to inject the value in template

if the value is string no quote need

<button th:data-id="${quartzInfo.id}" 
    th:onclick="del(this,[[${quartzInfo.id}]]" type="button">
</button>
查看更多
爷的心禁止访问
4楼-- · 2020-05-20 05:47

This should work:

<button th:onclick="'javascript:upload(' + ${gallery} + ')'"></button>
查看更多
冷血范
5楼-- · 2020-05-20 05:50

I solve this issue with this approach:

th:onclick="|upload('${command['class'].simpleName}', '${gallery}')|"
查看更多
够拽才男人
6楼-- · 2020-05-20 05:50

yes it's to late, but i hope this will help people who need it

try this

th:onclick="'upload('+${gallery}+')'"
查看更多
啃猪蹄的小仙女
7楼-- · 2020-05-20 05:51

thymeleaf 3.0.10 th:onclick thymeleaf variable not working

This should work:

th:attr="onclick=|upload('${gallery}')|" 
查看更多
登录 后发表回答