thymeleaf基础语法

2017-11-25  本文已影响22人  扒酒说

thymeleaf学习笔记

简单表达式

<div>
    <p>Name: <span th:text="${session.user.firstname}">Sebastian</span></p>
</div>
<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstname}">Sebastian</span></p>
</div>
<p th:utext="#{home.welcome}">Welcome to our grocery store ! </p>
<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>
<a th:href="@{~/tmp/logfile}">logfile</a>

文字类型

字符串操作

<span th:text="'The name of the user is ' + ${user.name}">
<span th:text="|The name of the user is  ${user.name}|">

数值型操作:

条件语句:

<body>
    <div th:if="${age} > 20">
        大于 20
    </div>
    <div th:unless="${age} > 20">
        小于 20
    </div>
</body>
<tr th:class="${row.even} ? 'even' : 'odd'">error</tr>
<div th:switch="${role}">
    <p th:case="user">User</p>
    <p th:case="${admin}">Admin</p>
    <p th:case="*">Unknown</p>
</div>

循环

<ul>
    <li th:each="animal : ${animals}" th:text="${animal}">小动物 - 此处文本会被覆盖</li>
</ul>

模版语法

<div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
    </div>
<div th:insert="~{footer :: copy}"></div>
<div th:replace="~{footer :: copy}"></div> 
<div th:include="~{footer :: copy}"></div>
<tbody th:remove="all-but-first"></tbody>

工具类

其他

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
<div th:object="${session.user}">
  ...
  <p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>
<div th:object="${session.user}">
  ...
  <p>Age: <span th:text="*{age}?-: '(no age specified)'">27</span>.</p>
</div>
context.setVariable(
     "users",
     new LazyContextVariable<List<User>>() {
         @Override
         protected List<User> loadValue() {
             return databaseRepository.findAllUsers();
         }
     });
context.setVariable(
     "users",
     new LazyContextVariable<List<User>>() {
         @Override
         protected List<User> loadValue() {
             return databaseRepository.findAllUsers();
         }
     });

参考文档

  1. 官方文档

  2. thymeleaf基础语法

上一篇 下一篇

猜你喜欢

热点阅读