ognl表达式 加 Thymeleaf【快速入门】(9)

电脑杂谈  发布时间:2019-01-03 01:05:30  来源:网络整理

再让Controller简单的传一个学生到前台:

@RequestMapping("/hello")
public String hello(Model model) {
    model.addAttribute("student", new Student("我没有三颗", 1));
    return "hello";
}

刷新项目,按下F12,就可以在控制台中看到正确的信息了:

代码解释:

通过th:inline="javascript"添加到script标签,这样JavaScript代码即可访问model中的属性,再通过[[${}]]格式来获得实际的值。

我们在开发中常常都把页面共同的header和footer提取出来,弄成单独的页面,然后让该包含的页面包含进来,我们就拿footer举例,首先在【templates】下新建一个要背其他页面包含的footer页面【include】:

<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1">
    <p>All Rights Reserved</p>
</footer>
<footer th:fragment="footer2(start,now)">
    <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>

然后直接在我们的hello.html页面中分别引用上面页面定义好的两个foot:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入门-Hello Thymeleaf</title>
</head>
<body>
<div th:include="include::footer1"></div>
<div th:replace="include::footer2(2015,2018)"></div>
</body>
</html>

刷新页面,可以看到效果:

代码解释:

我们可以使用th:fragment属性来定义被包含的模板片段,然后使用th:include和th:replace两个标签来直接引用标记好的片段,上面hello.html其实就相当于:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入门-Hello Thymeleaf</title>
</head>
<body>
<div>
    <p>All Rights Reserved</p>
</div>
<footer>
    <p>2015 - 2018 All Rights Reserved</p>
</footer>
</body>
</html>


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-91180-9.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 吴旭艳
      吴旭艳

      美方除了将部署空中巡逻和掩护配合此次行动外

    • 小林由美子
      小林由美子

      有勇有茅

    热点图片
    拼命载入中...