Thymeleaf classappend for multiple classes

2020-04-03 10:26发布

问题:

I want to add multiple classes using condition.

<div th:classappend="x.isTrue ?'class1' "  ></div>

I want something like

<div th:classappend="x.isTrue ?'class1' and "y.isTrue ?'class2'"  ></div>

回答1:

You can use literal substitutions to achieve this:

<div th:classappend="|${x.isTrue ? 'class1' : ''} ${y.isTrue ? 'class2' : ''}|"></div>

Another method is to simply wrap your conditions with brackets and concatenate them:

<div th:classappend="${(x.isTrue ? 'class1' : '') + (y.isTrue ? ' class2' : '')}"></div>


回答2:

Try this solution. It works very well for me.

<span class="oi" th:classappend="${(h.tipo.label =='Sim/Não' ? 'oi-signpost': '') + 
                                (h.tipo.label =='Quantidade' ? 'oi-target': '')+
                                 (h.tipo.label =='Evitar' ? 'oi-shield': '')}"
                                 title="Visualizar"
                                    aria-hidden="true"></span>