Search code examples
thymeleaf

Thymleaf, value of a variable set to an attribute


I have this:

 <span th:if="${colorValue =='green'}">
        <h1 color: green;  text-align:center;">
            <span th:text="${title}"></span>:
        </h1>
        </span>

What I would like is, to remove the span tag and set something like <h1 color: ${colorValue} text-align:center;"> That means setting color attribute directly by colorValue. How do I do that?


Solution

  • First of all, <h1 color: green; text-align:center;"> looks nothing like valid HTML.

    Given you wanted to set css with conditional color you can utilize th:styleappend:

    <h1 th:styleappend="'color: ' + ${colorValue} + '; text-align:center;'">
        <span th:text="${title}"></span>:
    </h1>
    
    

    Given you wanted to set attribute "color" you can utilize th:attr:

    <h1 th:attr="color=${colorValue}">
        <span th:text="${title}"></span>:
    </h1>