简体   繁体   中英

Multiple if else conditions in Thymeleaf

I'm trying to append a css class depending on multiple if cases with the ternary operator.

Is my ternary wrong?

I get the below error:

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression error.

If I look up the doc or other posts here I couldn't find a correct solution.

My code is the following:

 <table> <tr th:each="product: ${products}"> <th th:text="${product.status}" th:classappend=" ${product.status == 0}? class1: ${product.status == 1}? class2: ${product.status == 2}? class3: ${product.status == 3}? class4: class5"> </th> <table>

Ternary Operator is an operator that operates on three operands.

An expression a? b: c a? b: c evaluates to b if the value of a is true, and otherwise to c .

In your code:

<table>
    <tr th:each="product: ${products}">

    <th th:text="${product.status}"
        th:classappend="
           ${product.status == 0} ? class1 :
           ${product.status == 1} ? class2 :
           ${product.status == 2} ? class3 :
           ${product.status == 3} ? class4 : class5">
    </th>
<table>

how many operands you have after your first : ? or to be more precise, what is the expression you have after that colon?

If you have a composite expression, and your false candidate value is another ternary operator, you will have to let the engine parse your composite expression, including its nested operators, as:

a ? b : c

therefore, you have to group your chained nested operators as:

<table>
    <tr th:each="product: ${products}">
        <th th:text="${product.status}" th:classappend="
            ${product.status == 0} ? class1 :
            (${product.status == 1} ? class2 :
            (${product.status == 2} ? class3 :
            (${product.status == 3} ? class4 : class5)))">
        </th>
</table>

I found a solution:

wrapping the other conditions in ()

like this:

 <table> <tr th:each="product: ${products}"> <th th:text="${product.status}" th:classappend=" ${product.status == 0}? class1: (${product.status == 1}? class2: (${product.status == 2}? class3: (${product.status == 3}? class4: class5")))> </th> <table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM