[SpringBoot2.4.3] Thymeleafインライン・レイアウト1

controller

1
2
3
4
5
6
7
8
9
@RequestMapping("/{id}")
public ModelAndView index(@PathVariable int id, ModelAndView mav) {
    mav.setViewName("index");
    mav.addObject("id", id);
    mav.addObject("check", id % 2 == 0);
    mav.addObject("trueVal", "Even number!");
    mav.addObject("falseVal", "Odd number...");
    return mav;
}
1
<p th:text="${id} + ' is '+ (${check} ? ${trueVal} : ${falseVal})"></p>


thymeleaf側で計算すると不思議な感じするなー

1
2
3
4
5
6
7
8
9
@RequestMapping("/{id}")
public ModelAndView index(@PathVariable int id, ModelAndView mav) {
    mav.setViewName("index");
    mav.addObject("id", id);
    mav.addObject("check", id  >= 0);
    mav.addObject("trueVal", "POSITIVE!");
    mav.addObject("falseVal", "negative...");
    return mav;
}
1
2
<p th:if="${check}" th:text="${id} + ' is ' + ${trueVal}">message.</p>
<p th:unless="${check}" th:text="${id} + ' is ' + ${falseVal}">message.</p>

なんやこれ

1
2
3
4
5
6
7
8
9
@RequestMapping("/{month}")
public ModelAndView index(@PathVariable int month, ModelAndView mav) {
    mav.setViewName("index");
    int m = Math.abs(month) % 12;
    m = m == 0 ? 12 : m;
    mav.addObject("month", m);
    mav.addObject("check", Math.floor(m / 3));
    return mav;
}
1
2
3
4
5
6
7
8
9
<p th:if="${check}" th:text="${id} + ' is ' + ${trueVal}">message.</p>
<div th:switch="${check}">
    <p th:case="0" th:text="|${month} - Winter|"></p>
    <p th:case="1" th:text="|${month} - Spring|"></p>
    <p th:case="2" th:text="|${month} - Summer|"></p>
    <p th:case="3" th:text="|${month} - Autumn|"></p>
    <p th:case="4" th:text="|${month} - Winter|"></p>
    <p th:case="*">...?</p>
</div>

なんやこれは。。。普段きちんとコーディングしているかどうか一発でわかるな。ビビるわ。