如何使用 Thymeleaf 动态设置 HTML 元素的 id 属性

新手上路,请多包涵

假设我有一个对象:${object}

我有以下表格:

 <form id="{{'myForm' + object.id}" class="some class"
      th:action="@{/doSomething}" method="post">
    ....
</form>

如果我们假设 object.id 为“1”,我的目标是设置 id = “myForm1”。

PS:我写它的方式是在 Angular JS 上工作。

原文由 Lazar Lazarov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

你必须使用 th:id 属性:

 <form th:id="'myForm' + ${object.id}" class="some class" th:action="@{/doSomething}" method="post">
// *** Other code here ***
</form>

原文由 Sergio Garcia Alonso 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下是如何将动态 ID 与标签一起使用:

         <th:block th:with="randomId=${#strings.randomAlphanumeric(10)}">
            <input type="checkbox" th:id="${randomId}">
            <label th:for="${randomId}"></label>
        </th:block>

原文由 rgrebski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题