Lekan Swansons
Lekan Swansons

Reputation: 51

Thymeleaf style attribute

I am working with thymleaf and I am trying to apply style directly from a spring object. I am trying to use the th:style attribute and pass in the value directly from the pojo.

I found this code online that works

th:style="${color == 'yellow' ? 'background:yellow' : 'background:blue'}"

But I want to pass in the value direct from the object.

Like this

th:style="${color == 'yellow' ? 'background:${color}' : 'background:blue'}"

or like this directly

th:style="background:${color}"

both ways throw up errors.

Any help appreciated.

Upvotes: 0

Views: 1944

Answers (2)

nguyenpt
nguyenpt

Reputation: 21

Why you don't use th:class="${color == 'yellow' ? 'yellowClass' : 'blueClass'}" And style to both class. If you already have class attr, you can using th:classappend

Upvotes: 0

Metroids
Metroids

Reputation: 20487

The Thymeleaf docs have many examples of String concatenation... the easiest in this case would be literal substitution.

th:style="|background: ${color}|"

but you can just use a regular string concatenation as well.

th:style="${'background: ' + color}"

Upvotes: 3

Related Questions