Springboot thymeleaf实战总结
介绍
以下总结了使用Thymeleaf做项目过程中碰到的有价值的知识点。拿出来分享!
1.配置context-path
- 在公共模板中添加:
<script type="text/javascript" th:inline="javascript" th:fragment="ctx">
/*<![CDATA[*/
var ctx = /*[[@{/}]]*/ '';
/*]]>*/
</script>
- 在需要ctx的页面中添加
<!--ctx-->
<script th:replace="~{fragment::ctx}"/>
2.遍历list
<a th:each="n,newsStat : ${newsList}" th:href="|/news/${n.id}|"
class="list-group-item">
<h5 class="mb-1" th:text="${n.getTitle()}">时政微视频丨与光同行</h5>
<small th:text="${n.getCreateTime()}">2021.12.1,阅读:123</small>
</a>
- 状态变量
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
3.th:href字符串和变量混合拼接
th:href="|/list?l=${lid}|"
4.datetime格式化
th:text="${#dates.format(n.createTime,'yyyy-MM-dd HH:mm:ss')}"
5.输出html内容
<div class="col-9" th:utext="${news.content}"></div>
6 下拉选择列表
/**
* 新增新闻
*/
@GetMapping("/add")
public String add(ModelMap map)
{
// 新闻分类列表
map.put("newsTypeList",newsTypeService.selectDmNewsTypeList(null));
return prefix + "/add";
}
- 新增
<div class="form-group">
<label class="col-sm-3 control-label">新闻分类:</label>
<div class="col-sm-8">
<!--<input name="newsTypeId" class="form-control" type="text">-->
<select name="newsTypeId" id="newsTypeId" lay-verify="required" class="form-control">
<option th:each="t:${newsTypeList}" th:value="${t.id}"
th:text="${t.typeName}"></option>
</select>
</div>
</div>
- 编辑回显
<select name="newsTypeId" id="newsTypeId" lay-verify="required" class="form-control">
<option th:each="t:${newsTypeList}" th:value="${t.id}"
th:text="${t.typeName}"></option>
</select>