【问题标题】:How can I add hyperlinks to columns of a table using thymeleaf th:each?如何使用 thymeleaf th:each 将超链接添加到表的列?
【发布时间】:2021-04-24 03:37:37
【问题描述】:

我正在尝试为 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>

上面的代码为我提供了表格外生成的超链接的输出。

这是生成的 html 的链接。 https://i.gyazo.com/7dae68eb42cd084b59030e7b17590e5e.png

“linklinklinklink”是生成的超链接的输出。我希望“名字”列成为超链接。 如果有人能告诉我如何做到这一点,那就太好了。

【问题讨论】:

    标签: java html html-table hyperlink thymeleaf


    【解决方案1】:

    将您的&lt;a&gt; 标签放在您希望链接出现的&lt;td&gt; 单元格中:

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

    请注意如何在&lt;a&gt; 标记内使用th:text="..." 属性来控制链接的可见文本。

    在您的情况下,您在一行中有一个 &lt;a&gt; 标记,但不是任何单元格的一部分。这是无效的 HTML,因此您的浏览器的 HTML 渲染器将链接转储到其他地方(在这种情况下,在表格上方)。

    【讨论】:

    • 非常感谢,这正是问题所在。我不敢相信我没有注意到不正确的 HTML 语法。
    • 不客气。旁注:如果您还没有这样做,我建议您访问该网站tour
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    相关资源
    最近更新 更多