Home > Net >  Set CSS variables from model object in Thymeleaf
Set CSS variables from model object in Thymeleaf

Time:12-13

I'm setting CSS color variables inside a style tag in a Thymeleaf template. The color values are coming from the model object. I also want to apply a default color, in case the model attirbute is not there.

I already used the correct Answer in Question 62610602 but in my case a backslash is pasted in front of the color code. This defenetly isn't comming from the given String

:root {
    --accent-color: \#00FF00;
}

The Code in the Thymeleaf template is:

<style th:inline="css">
    :root {
        --accent-color: [[${appUser?.accentColorCode} ?: '#ea0a8e']];
    }
</style>

CodePudding user response:

Looks like [[...]] css expressions escape output as CSS identifiers. You'll have to use the unescaped [(...)] expression to output colors. (I've edited my original answer...)

<style th:inline="css">
    :root {
        --accent-color: [(${appUser?.accentColorCode} ?: '#ea0a8e')];
    }
</style>
  • Related