我可以用 Thymeleaf 设置 data-* 属性吗?
正如我从 Thymeleaf 文档中了解到的那样,我尝试过:
<div th:data-el_id="${element.getId()}"> <!-- doesn't work -->
<div data-th-el_id="${element.getId()}"> <!-- doesn't work -->
原文由 Alexandru Severin 发布,翻译遵循 CC BY-SA 4.0 许可协议
我可以用 Thymeleaf 设置 data-* 属性吗?
正如我从 Thymeleaf 文档中了解到的那样,我尝试过:
<div th:data-el_id="${element.getId()}"> <!-- doesn't work -->
<div data-th-el_id="${element.getId()}"> <!-- doesn't work -->
原文由 Alexandru Severin 发布,翻译遵循 CC BY-SA 4.0 许可协议
With Thymeleaf 3.0 there is the Default Attribute Processor which can be used for any kind of custom attributes, eg th:data-el_id=""
becomes data-el_id=""
, th:ng-app=""
becomes ng-app=""
等等。不再需要心爱的数据属性方言。
我更喜欢这个解决方案, 如果我想使用 json 作为值,而不是:
th:attr="data-foobar='{"foo":'+${bar}+'}'"
您可以使用(结合 文字替换):
th:data-foobar='|{"foo":${bar}}|'
更新: 如果您不喜欢 th
命名空间,您也可以使用 HTML5 友好的属性和元素名称,例如 data-th-data-foobar=""
。
如果有人感兴趣,可以在这里找到相关的模板引擎测试: 默认属性处理器测试
原文由 RiZKiT 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答1.5k 阅读✓ 已解决
2 回答882 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
1 回答899 阅读✓ 已解决
2 回答783 阅读
1 回答771 阅读✓ 已解决
2 回答1.1k 阅读
是的,
th:attr
救援 Thymeleaf 文档 - 设置属性值。对于您的场景,这应该可以完成工作:
XML 规则不允许您在标记中设置两次属性,因此在同一元素中不能有多个
th:attr
。注意:如果您想要多个属性,请用逗号分隔不同的属性: