在Thymeleaf中创建空数据属性

时间:2017-03-21 18:52:39

标签: html5 thymeleaf custom-data-attribute

我尝试使用自定义数据属性在Thymeleaf 3.0.3(Spring 4.3.7)中创建元素:

<input th:attr="data-customAttr=${item.getMyAttr()}" />

如果item.getMyAttr()的结果是&#39; someVal&#39;,那么渲染的HTML就会出现:

<input data-customAttr='someVal' />

但是,如果item.getMyAttr()的结果是空字符串,则Thymeleaf会完全抛出自定义属性。呈现的HTML看起来像:

<input />

我需要知道自定义属性是否已定义,是否为空或缺失且未定义。根据这个讨论:Are empty HTML5 data attributes valid? ,空数据属性应该完全有效。

经过一番挖掘后,我遇到了以下测试用例,似乎表明Thymeleaf无法呈现空数据属性,这就是为什么它在渲染时间之前将它们抛出的原因。以下Thymeleaf片段呈现得很好:

<input th:attr="__${'data-customAttr=' + 'someVal'}__" />

虽然这两个都会引发错误:

<!-- Throws: 'org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as assignation sequence' -->
<input th:attr="__${'data-customAttr=' + ''}__" />
<input th:attr="__${'data-customAttr'}__" />

这是Thymeleaf的错误吗?任何帮助将不胜感激。我也乐意提供任何其他相关信息。

编辑:这是我在相当大的应用程序中大量使用的功能。虽然我知道有几种解决方法,但它们都会增加我必须编写/维护的代码量,以完成一项非常简单的任务。我希望有一个长期的解决方案,即使该解决方案是&#34;这是一个错误,请报告&#34;。

1 个答案:

答案 0 :(得分:1)

__语法不是特别的......它只是让它运行评估器两次。它不起作用的原因是因为在每种情况下,它都解决了无效的百里叶表达。

例如:

<input th:attr="__${'data-customAttr=' + ''}__" />
<!-- evaluates to -->
<input th:attr="data-customAttr=" />
<!-- which is an invalid expression -->

相同
<input th:attr="__${'data-customAttr'}__" />
<!-- evaluates to -->
<input th:attr="data-customAttr" />
<!-- which is again, an invalid expression -->

看起来百里香叶似乎不会增加空洞的属性。所以我认为你要做的最好就是这样:

<input th:attr="data-customAttr-exists=${item.getMyAttr() != null}, data-customAttr=${item.getMyAttr()}" />

并且您必须检查第一个属性以确定它是否存在,以及该值的第二个属性。这应该可以让你了解所有情况。