2

I want to use Thymeleaf to pass a value to data from Bootstrap.

I don't know how to do it. Can you help me?

<tr th:each="car : ${lCars}" class="succes">
  <td th:text="${car.id}"></td>
  <td th:text="${car.name}"></td>
  <td align="center">

    <button type="button" class="btn btn-primary"
      data-toggle="modal" data-target="#editar" title="Edit"
      data-id= "th:text="${car.id}""    <!-- I want to pass this value on to the data, but this way doesn't work -->
      data-name="myCar" <!-- If I send a simple word, works well -->

      <span class="glyphicon glyphicon-pencil"></span> Edit
    </button>
  </td>
</tr>
Reiko
  • 23
  • 3

1 Answers1

4

The following line makes no sense: data-id="th:text="${car.id}""

  1. The purpose of th:text is to modify the body text of the element (in this case, a button element). You're trying to set an attribute value.
  2. If you want thymeleaf to modify a data attribute like data-id, you need to th:attr instead

That line should be written as follows:

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

If you want the data-id to have some default value like "example-id", do this:

data-id="example-id" th:attr="data-id=${car.id}"
Greg
  • 561
  • 3
  • 9
  • Thanks for your answer. What i should i do if i want to add another attribute to the same button? data-id="" th:attr="data-id=${car.id}" example: data-name="" th:attr="data-name=${car.name}" Because it works well with one attribute, but when i add other data i have problems, because the first attribute was assigned to the button i hope you can help me – Reiko Jun 26 '17 at 19:45
  • 1
    To solve this i used: th:attr="data-id=${car.id},data-name=${car.name}" – Reiko Jun 26 '17 at 20:17
  • 1
    Reiko, you are the boss giving me the idea to list them with comma! thanks – AlexGera Mar 26 '20 at 02:58