Search code examples
htmlthymeleaf

Calling javascript function with parameters from thymeleaf


I need to call a javascript function from html using thymeleaf. In this particular case I have a student object and I need to pass this student object to a javascript function (edit()) for processing on button click.

Important code segments:

<form action="/addStudent" method="post">
Name:<br>
<input type="text" id="name" name="name"><br>
<input type="submit" value="Submit"></form>


<table>
<tr>
    <th>ID</th>
    <th>Name</th>
</tr>
<tr th:each="student : ${students}">
    <td th:text="${student.id}"></td>
    <td th:text="${student.name}"></td>

    <td>
        <button type="button" th:onclick="'edit(\'' + ${student} + '\');'">Edit</button>
    </td>
</tr></table>

<script type="text/javascript">
function edit(student)
{
    console.log("--------------------edit---------------------" + student.name);
}</script>

But it doesn't work as expected. It shows the following error. Can anyone help by showing how to pass student object from thymeleaf to javascript function?

There was an unexpected error (type=Internal Server Error, status=500).An error happened during template parsing (template: "class path resource [templates/students.html]") org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/students.html]")


Solution

  • For security reasons you've to define the parameter to use as a data attribute (in the newest versions of thymeleaf). Do it in the following way:

    th:data-student="${student}" th:onclick="edit(this.getAttribute('data-student'))"