Thymeleaf中使用“fragment” | 青训营笔记

84 阅读1分钟

今天是我参加【第四届青训营】笔记创作活动第11天

定义“fragment”

在Thymeleaf中,通过Template布局实现模板的重用,在模板定义的时候需要用到thymeleaf提供的 th:fragment 属性。直接用html编写的时候还是需要在文件的html标签中添加命名空间。这里我将html文件全部放入templates文件中,公共文件放入templates文件下的commons文件夹下,新建存放公共html的commons.html文件(公共文件路径templates/commons/commons.html)。在commons.html中定义公共模块:

<!DOCTYPE html>
<html xmls:th="http://www.thymeleaf.org">
<body>
    <div th:fragment="float1-navigation">
    ...
    </div>
    ...
</body>
</html>

引用“fragment”

定义好了公共模块,就可以在其它的html的文件中引用模块了。在文件templates/homepage.html中引用公共模块:

<!DOCTYPE html>
<html lang="en" xmls:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
    <div th:replace="
~{commons/commons::float1-navigation}
"></div>
    ...
</body>
</html>

这里的th:replace也可以是th:insert或者是th:include也行。 th:replace是用模板的

标签完全替换掉引用的
标签,效果为
...
th:insert是将模板标签直接插入引用的
标签中,效果为
...
th:include是将模板中的内容放入引用的标签中,效果为
...
(这里的标签
不是模板文件中的
,这也是与th:replace的区别)

在定义模块的时候还可以传递参数:

<!DOCTYPE html>
<html xmls:th="http://www.thymeleaf.org">
<body>
    <div th:fragment="float1-navigation (p1,p2)">
    ...
    </div>
    ...
</body>
</html>

引用模块的时候带参数 第一种方式:

<!DOCTYPE html>
<html lang="en" xmls:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
    <div th:replace="
~{commons/commons::float1-navigation (value1,value2)}
"></div>
    ...
</body>
</html>

第二种方式:

<!DOCTYPE html>
<html lang="en" xmls:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
    <div th:replace="
~{commons/commons::float1-navigation (p1=value1,p2=value2)}
"></div>
    ...
</body>
</html>

第二种方式的参数传递方式与顺序无关,第一种的参数顺序与模块定义的顺序应该保持一致。

标题:Tutorial: Using Thymeleaf

网址:www.thymeleaf.org/doc/tutoria…