Html 将 data-* 属性与百里香叶一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24411826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:08:37  来源:igfitidea点击:

using data-* attribute with thymeleaf

htmlthymeleaf

提问by Alexandru Severin

Can I set data-* attribute with thymeleaf?

我可以用 thymeleaf 设置 data-* 属性吗?

As I understood from thymeleaf documentation I tried:

正如我从 thymeleaf 文档中了解到的,我尝试过:

<div th:data-el_id="${element.getId()}"> <!-- doesn't work -->

<div data-th-el_id="${element.getId()}"> <!-- doesn't work -->

回答by Aldrian

Yes, th:attrto the rescue Thymeleaf documentation - Setting attribute values.

是的,th:attr拯救Thymeleaf 文档 - 设置属性值

For your scenario, this should do the job:

对于您的场景,这应该可以完成工作:

<div th:attr="data-el_id=${element.getId()}">

XML rules do not allow you to set an attribute twice in a tag, so you can't have more than one th:attrin the same element.

XML 规则不允许您在一个标签中两次设置一个属性,因此您不能th:attr在同一元素中设置多个属性。

Note: If you want more that one attribute, separate the different attributes by comma:

注意:如果您想要多个属性,请用逗号分隔不同的属性:

<div th:attr="data-id=${element.getId()},data-name=${element.getN??ame()}"> 

回答by Adrian Ber

Or you can use this Thymeleaf dialect https://github.com/mxab/thymeleaf-extras-data-attributeand you'll be able do

或者你可以使用这个 Thymeleaf 方言https://github.com/mxab/thymeleaf-extras-data-attribute你就可以了

<div data:el_id="${element.getId()}">

回答by RiZKiT

With Thymeleaf 3.0 there is the Default Attribute Processorwhich can be used for any kind of custom attributes, e.g. th:data-el_id=""becomes data-el_id="", th:ng-app=""becomes ng-app=""and so on. There is no need for the beloved data attribute dialect anymore.

Thymeleaf 3.0 有默认属性处理器,可用于任何类型的自定义属性,例如th:data-el_id=""变成data-el_id=""th:ng-app=""变成ng-app=""等等。不再需要心爱的数据属性方言。

This solution I prefer, if I want to use jsonas the value, instead of:

我更喜欢这个解决方案,如果我想使用 json作为值,而不是:

th:attr="data-foobar='{&quot;foo&quot:'+${bar}+'}'"

You can use (in combination with literal substitution):

您可以使用(与文字替换结合使用):

th:data-foobar='|{"foo":${bar}}|'

Update:If you don't like the thnamespace, you can also use HTML5 friendly attribute and element nameslike data-th-data-foobar="".

更新:如果你不喜欢th命名空间,你也可以使用HTML5 友好的属性和元素名称,data-th-data-foobar="".

If someone is interested, related template engine tests can be found here: Tests for Default Attribute Processor

如果有人感兴趣,可以在这里找到相关的模板引擎测试:Tests for Default Attribute Processor