Search code examples
htmlthymeleaf

Thymeleaf dynamic list setter


I would like to simplify some code of mine. It's quite simple honestly. I have 1 input field, and if a certain condition is fulfilled, it should have 1 more attribute. It should have the list attribute. The Problem I'm having is, that I don't know how to dynamically set an attribute.

The code looks like this currently:

           <input th:if="${fieldIndex == 0 && !#arrays.contains(dropDownFields, y)}"
                   th:disabled="${#arrays.contains(disabledFields, y)}"
                   th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}"
                   class="table-input" type="text" onfocus="focused(this)">

            <input th:if="${fieldIndex == 0 && #arrays.contains(dropDownFields, y)}"
                   list="list"
                   th:disabled="${#arrays.contains(disabledFields, y)}"
                   th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}"
                   class="table-input" type="text" onfocus="focused(this)">

And as you can see, the 2 input fields are the exact same, except when this condition is true: #arrays.contains(dropDownFields, y), then it should also add the attribute list="list". Is there any easier way than copying so much code?

Any help would be appreciated, thank you!


Solution

  • Instead of using th:if you can use th:attr and place the conditional logic in that attribute using the Thymeleaf "if-then-else" operator: (if) ? (then) : (else).

    Here is a simplified version of your code showing this:

    <input th:attr="list=${#arrays.contains(dropDownFields, y) ? 'some_value' : null}">
    

    If the #arrays.contains condition is true, then the list attribute will be added to the <input> element; otherwise if the condition is false, and the null is returned, then no attribute will be added.

    Instead of 'some_value' you can use whatever you want - including the th:field expression from your question.

    All the other attributes in your question can be included in the tag, and will be unaffected, since they are not part of the (if) ? (then) : (else) logic.