【问题标题】:thymeleaf - combined th:each with th:hrefthymeleaf - 结合 th:each 和 th:href
【发布时间】:2023-03-31 13:00:02
【问题描述】:

我是 Thymeleaf(和 webdev)的新手,我正在尝试将 Thymeleaf 迭代 (th:each) 与 URL 重写 (th:href) 结合起来。

<a th:each="lid : ${lists}" th:text="${lid}" th:href="@{/list?l=${lid}}">
hello
</a>

这会产生以下结果(其中 lid=45):

<a href="/list?l=${lid}">45</a>

所以,它在 th:text 上进行了替换,但在 th:href 上没有。

我不想做任何形式的 URL 重写,我只是使用 '@' 语法,因为我希望 Thymeleaf 替换 'lid' 属性。

我在 Google App Engine 中使用当前版本的 Thymeleaf (2.1.2)。

【问题讨论】:

    标签: java thymeleaf


    【解决方案1】:

    如果您不想进行任何 url 重写,则不应使用 @ 语法。

    您可以使用管道 (|) 语法进行一些文字替换:

    th:href="|/list?l=${lid}|"
    

    来源:Thymeleaf documentation

    【讨论】:

      【解决方案2】:

      你也可以这样试试:

      <a th:href="@{'/list?l=' + ${lid}}" th:text="${lid}">element</a>
      

      【讨论】:

        【解决方案3】:

        我没有足够的声誉来为之前的帖子添加评论,但之前帖子中的 Thymeleaf 源文档链接已损坏。现在可以在以下链接中找到文档:

        Thymeleaf Standard URL Syntax

        本文档中的第 9 节在 URL 中使用表达式解释了在使用 @ 语法生成 URL 时如何在其他表达式中使用表达式。下面是一个例子:

        <a th:href="@{/order/details(id=${modelattribute})}"/>
        

        会产生一个类似的链接:

        http://domain.org/context/order/details?id=1
        

        如果模型属性在当前上下文中的值为 1。

        【讨论】:

        • 按照我最终使用的链接:th:href="@{main/{sectionId}(sectionId=${section.id})},它将sectionId 替换为${section.id},输出例如main/12345
        猜你喜欢
        • 2014-12-07
        • 2018-01-07
        • 2018-05-09
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 2020-10-09
        • 2016-07-16
        相关资源
        最近更新 更多