thymeleaf-docs icon indicating copy to clipboard operation
thymeleaf-docs copied to clipboard

如何th:class中根据多个条件或者一个条件给class进行多属性的赋值

Open 1115750935 opened this issue 5 years ago • 1 comments

比如 当状态为1时,class是 container green
状态为2时且状态为3时, class 是container red
状态为4时,class 为container blue
以前用的是jsp页面,在class属性中 c:if就可以,但是使用thymeleaf模板之后,无法实现这个效果.求大神,

1115750935 avatar Jan 25 '21 09:01 1115750935

Hi there, unfortunately I don't speak Chinese, so am going to attempt an answer through Google Translate - I hope this works!

It seems like you're asking about applying a class to an element in Thymeleaf based on the value of some status. With JSPs you could use c:if to do that. In Thymeleaf, one way you can do this is using a variable expressions inside the th:class attribute processor.

Example:

<div th:class="${status == 1 ? 'green' : status == 2 || status == 3 ? 'red' : status == 4 ? 'blue' : ''}">

So if status was 1 you'd end up with <div class="green">, if it's 2 or 3 then <div class="red">, or if it's 4 then <div class="blue">.

Expressions are pretty powerful, so learning to use them will help you out. The expression syntax used depends on whether you're using Spring or not, but they're very similar:

  • If you're using Spring, then it's the Spring Expression Language being used: https://www.baeldung.com/spring-expression-language
  • If you're not using Spring, then it's OGNL: http://commons.apache.org/proper/commons-ognl/language-guide.html

ultraq avatar Jan 26 '21 09:01 ultraq