片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是JSP无法做到的。
片段表达式拥有三种语法:
~{ viewName } 表示引入完整页面~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等~{ ::selector} 表示在当前页寻找
使用方法:首先通过th:fragment定制片段 ,然后通过th:replace 填写片段路径和片段名。例如:
<!-- /views/common/head.html--><head th:fragment="static"><script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script></head><!-- /views/your.html --><div th:replace="~{common/head::static}"></div>
在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:
<!-- your.html -->
<div th:replace="common/head::static"></div>
值得注意的是,使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/)。
