Thymeleaf - 获取dom元素属性

时间:2018-03-30 08:07:41

标签: html thymeleaf

我使用Thymeleaf创建html组件。组件在单独的文件中声明:

buttons.html

中的基本按钮声明
<div th:fragment="btn-basic" class="btn btn-basic" th:text="${text}" th:classappend="${class}">
    Button
</div>

我们的想法是为组件提供某种类型的工具集。使用此组件的代码将是:

<div th:replace="~{buttons :: btn-basic (text='Button Text', class='button-class')}"></div>

它运行良好,但我想到按钮需要具有以下属性的情况:onclick="..."data-customAttr="..."或任何其他属性。这就是问题所在:

  • 如何将属性传递给按钮?
  • 一种方法是将它作为片段的参数传递,但它太丑了。
  • 有没有办法在片段中获取占位符的属性? (见下面的例子)

这是我想调用片段的方式:

<div th:replace="~{buttons :: btn-basic (text='Button Text', class='button-class')}" onclick="..." data-customAttr="..."></div>

并且在btn-basic片段中想要获取这些属性并附加到它。像这样:

<div th:fragment="btn-basic" class="btn btn-basic" th:text="${text}" th:classappend="${class}" onclick="..." data-customAttr="...">
    Button
</div>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我有一个类似的想法,但是问题是,如果组件的定制与结果一样复杂,那么有什么好处?

顺便说一句。使用Thymeleaf Layout Dialect,您可以执行以下操作:https://ultraq.github.io/thymeleaf-layout-dialect/Examples.html#reusable-templates,我赞成这样做,而不是使用“按参数设置一切”的方法。

相关问题