1.写在前面

th:inline 有三个取值类型 (text, javascript 和 none),值为 none 什么都不做,没有效果。

所以这里只对前两个取值类型(text、javascript)做一个举例。


2.应用举例

2.1 内敛文本(th:inline=”text” )

内敛文本表达式不依赖于 html 标签,直接使用 内敛表达式 [ [ 表达式] ] 即可获取动态数据,但必须要求在父级标签上加 th:inline = “text”属性。

2.2 内敛脚本(th:inline=”javascript” )

th:inline=”javascript” 在 js 代码中获取后台的动态数据。

2.3 代码

首先是一个控制层类,其中有一个请求方法。

package com.songzihao.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 */
@Controller
public class UserController {

    @RequestMapping(value = "/inline")
    public String inline(Model model) {
        model.addAttribute("data","SpringBoot inline");
        return "inline";
    }
}

然后是这个请求方法对应的html页面。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf">
<head>
    <meta charset="UTF-8">
    <title>内敛表达式</title>
</head>
<body>
    <h2>内敛文本:th:inline="text"</h2>
    <div th:inline="text">
        数据:[[${data}]]
    </div>
    <hr/>
    <h2>内敛脚本:th:inline="javascript"</h2>
    <script type="text/javascript" th:inline="javascript">
        function showData() {
            alert([[${data}]]);
        }
    </script>
    <button th:onclick="showData()">点击我</button>
</body>

</html>

我们还需要在核心配置文件中关闭Thymeleaf的缓存开关。最后启动测试。

spring.thymeleaf.cache=false
package com.songzihao.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

 

更多推荐

SpringBoot——Thymeleaf中的th:inline(内敛文本text、内敛脚本javascript)