Creating empty data-attributes in Thymeleaf

谁说胖子不能爱 提交于 2019-12-14 03:57:57

问题


I'm attempting to create an element in Thymeleaf 3.0.3 (Spring 4.3.7) with a custom data-attribute:

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

If the result of item.getMyAttr() was 'someVal', then the rendered HTML comes out to be:

<input data-customAttr='someVal' />

However, if the result of item.getMyAttr() is an empty string, the custom attribute is thrown out by Thymeleaf altogether. The rendered HTML looks like:

<input />

I need to know whether the custom attribute was defined and empty or missing and undefined. According to this discussion: Are empty HTML5 data attributes valid? , empty data-attributes should be perfectly valid.

After a little digging I ran into the following test case that seems to show Thymeleaf can't render empty data-attributes, which is why it's throwing them out before render-time. The following Thymeleaf snippet renders just fine:

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

While both of these throw an error:

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

Is this a bug in Thymeleaf? Any help would be greatly appreciated. I'm happy to provide any other relevant information as well.

Edit: This is a feature I'm making heavy use of in a fairly large application. While I'm aware that there are several workarounds, they all compound the amount of code I have to write/maintain just to accomplish a very simple task. I'm hoping for a long-term solution, even if that solution is "This is a bug, please report it".


回答1:


The __ syntax isn't anything special... it just makes it run the evaluator twice. The reason it doesn't work is because in each case, it resolves to an invalid thymeleaf expression.

For example:

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

Same with

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

It does appear that thymeleaf won't add empty attributes. So I think the best you are going to do is something like this:

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

And you'll have to check the first property to know whether or not it exists, and the second property for the value. This should allow you to know all cases.



来源:https://stackoverflow.com/questions/42935823/creating-empty-data-attributes-in-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!