简体   繁体   中英

How can I add hyperlinks to columns of a table using thymeleaf th:each?

I'm trying to create hyperlinks for each element in a table generated by thymeleaf.

<tbody>
    <tr th:each="author :${authors}">
        <td th:text="${author.id}"></td>
        <a th:href="@{/authors/{id}(id=${author.id})}">
            <td class="authorLink" th:text="${author.firstName}"></td>
        </a>
        <td th:text="${author.lastName}"></td>
    </tr>
</tbody>

The code above is giving me an output of the generated hyperlinks outside of the table.

This is a link to the generated html. https://i.gyazo.com/7dae68eb42cd084b59030e7b17590e5e.png

"linklinklinklink" is the output of the generated hyperlinks. I would like for the 'First Name' column to become hyperlinks. If anyone can tell me how I can accomplish this that would be great.

Place your <a> tag inside the <td> cell where you want the link to appear:

<td>
    <a th:href="@{/authors/{id}(id=${author.id})}" 
       th:text="${author.id}"></a>
</td>

Note how you can use a th:text="..." attribute inside the <a> tag, as well, to control the visible text for the link.

In your case, you had a <a> tag inside a row, but not part of any cell. This is invalid HTML, so your browser's HTML renderer dumped the links somewhere else (above the table, in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM