(7)thymeleaf的使用

引入thymeleaf:

在pom.xml中引入就可以了:

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

thymeleaf的使用

HTML文件放在templates文件夾下就可以了。

在controller中:

//查出一些數據在界面中顯示

    @RequestMapping("/success")

    public String success(Map<String,Object>map){

        //在類路徑下的templates/success.html

        map.put("hello","<h1>你好</h1>");

        map.put("users", Arrays.asList("zhangsh","jiangyi"));

        return "success";

    }

在html中獲得數據:

1,先導入thymeleaf的命名空間(不導入也可以,就是沒有提示,所以爲了方便還是導入吧)

2.使用:

<html  lang="en" xmlns:th="http://www.thymeleaf.org">

 

th:text:是可以指定內容的,即使之前HTML中有內容,也會被這個內容覆蓋。

包括:th:id,th:class,也是同理,也是覆蓋原來HTML中的內容。

<h1>成功</h1>

<!--將div裏面的文本內容設置爲我們指定的值-->

<div id="hello" th:id="hello2" th:text="${hello}">

這是顯示歡迎信息

</div>

<div th:text="${hello}"></div>

<div th:utext="${hello}"></div>

<!--每次遍歷都會生成當前這個標籤3個h4-->

<h4 th:each="user:${users}" th:text="${user}"></h4>

<hr/>

<h4>

    <span th:each="user:${users}">[[${user}]]</span>

</h4>

[[ ]]等價於th:text

[{ }]等價於 th:utext

路徑的寫法

@{ }語法來引入路徑的好處:

以後如果我們需要更改項目名稱:

比如我們在配置文件中添加了:

server.contex-path:/crud,

那麼用@{}會自動加入/crud

注意:以後所有的路勁都要寫成這個形式,要不然有的時候會有404錯誤,特別是靜態資源。用/webjars的時候。

<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

根據這個來寫:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章