thymeleaf에 해당하는 글 1

[Spring][Thymeleaf] if else그리고 조건문

JAVA/Spring|2019. 5. 22. 19:30

Spring Boot에서 View를 주로 Thymeleaf를 사용하고 있다.

 

생각 안나는 것들은 필요할때마다 검색해서 사용하고 있기 때문에

 

정리해본다.

 

예제는 dutch 값이 모델에 있을경우 dutch.name을 확인 후 selected 세팅을 하도록

 

단순 if

<option  th:if="${dutch!=null}" 
th:each="coffee : ${T(com.meteor.coffee.CoffeeEnum).values()}" 
th:value="${coffee.name()}" th:text="#{${coffee.name()}+'.name'}"
th:selected="${coffee.name() == dutch.coffeeKind.name()}">
</option>

 

 

if-else

<option  th:if="${dutch!=null}" 
th:each="coffee : ${T(com.meteor.coffee.CoffeeEnum).values()}" 
th:value="${coffee.name()}" th:text="#{${coffee.name()}+'.name'}"
th:selected="${coffee.name() == dutch.coffeeKind.name()}">
</option>

<option  th:unless="${dutch!=null}" 
th:each="coffee : ${T(com.meteor.coffee.CoffeeEnum).values()}" 
th:value="${coffee.name()}" th:text="#{${coffee.name()}+'.name'}">
</option>

 

여기서 기억에 남는건 unless에 들어가는 조건이 위의 if 조건에 들어간것과 같아야 한다는것

 

 

추가적으로, 변수 내에서도 분기가 가능하다

<form method="post"> 에서 method를 분기 처리한다면

 

<form method="${dutch==null ? 'post':'put'}"> 처럼 표현이 가능하다.

물론 put은 

<input type="hidden" name="_method" value="put">

으로 표현되겠지만..

 

 

댓글()