Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
1115750935 opened this issue Jan 25, 2021 · 1 comment

Comments

@1115750935
Copy link

1115750935 commented Jan 25, 2021

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

@ultraq
Copy link
Member

ultraq commented Jan 26, 2021

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:

@ultraq ultraq self-assigned this Jan 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants