conditional css class include

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

conditional css class include

om.singh
I am trying to include a css class on condition and using the below code

        <div th:switch="${categoryStat.count}"> 
                <div th:case="1" th:with="cssclass='item-left'"/>           
  <div th:case="6" th:with="cssclass='last-item item-right'"/>
        </div>
       
        <li th:class="${cssclass}">

This is not working, as I am not able to set the cssclass correctly.

I am new to thymeleaf framework - in case you have suggestion or advice me the correct way of doing this - it will be great.

Om
Reply | Threaded
Open this post in threaded view
|

Re: conditional css class include

Zemi
Administrator
The variable set by th:with is only visible inside the element.

I can't figure out a clean solution, the following works:

    <li th:attr="class=${categoryStat.count == 1 ? 'item-left' : ''}"
         th:attrappend="class=${categoryStat.count == 6 ? 'last-item item-right' : ''}">

but you'd better move the logic outside the HTML, maybe

    <li th:class="'item-' + ${categoryStat.count}">

so you would have CSS classes 'item-1' and 'item-6', or maybe to Java

    <li th:class="${category.itemType}">

Reply | Threaded
Open this post in threaded view
|

Re: conditional css class include

om.singh
Thanks a lot Zemi,

I agree, moving it in java would be much better, but your solution works. It will be worth having some tags available in thymeleaf to handle "if elseif" kind of thing.

Regards
Om
Reply | Threaded
Open this post in threaded view
|

Re: conditional css class include

danielfernandez
Administrator
Remember there is also a th:classappend attribute specifically suited for appending additional CSS classes to an element without modifying the existing ones.