zoukankan      html  css  js  c++  java
  • Thymeleaf模板引擎的初步使用

    在springboot中,推荐使用的模板引擎是Thymeleaf模板引擎,它提供了完美的Spring MVC的支持。下面就简单的介绍一下Thymeleaf模板引擎的使用。

    在controller层中,使用在类上使用@controller注解,注意的是,这里不是@restController注解,因为@restController注解是将结果作为json字符串进行返回的,并不是调用模板。

    方法中,注入参数,Model model。然后同springmvc中的modelandview一样,model也提供了属性方法:addAttribute(“”,“”)。

    下面是在html页面的一些操作

    • 引入Thymeleaf

    在html标签中加入名称空间,将页面转换成动态的页面

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

    转换之后有一点需要注意,就是对于静态资源的访问也变了,静态资源需要通过th:src=“@{path}”进行访问。

    • 访问model中的数据,所有动态资源需要加上th前缀

    需要在标签中使用th:text="${singlePerson.age}进行访问,感觉不是很方便,以后还是尽量使用ajax进行异步操作吧

    <h2 th:text="${singlePerson.age}"></h2>
    • 数据迭代
    <ul>
            <li th:each="person:${list}">
                <h1 th:text="${person.name}"></h1>
            </li>
        </ul>
    • 数据的判断
    <ul th:if="${#lists.isEmpty(list)}">
            <li th:each="person:${list}">
                <h1 th:text="${person.name}"></h1>
            </li>
        </ul>

    通过${#lists.isEmpty(list)}表达式判断是否集合list为空。

    Thymeleaf支持>,<,>=,<=,!=等作为比较条件,同时也支持将SpringEL表达式用于条件之中,不过这个我没学过,具体就不知道怎么用了。

    • 在JavaScript中访问model
    <script type="text/javascript" th:inline="javascript">
        window.onload=function(){
            alert([[${singlePerson.name}]]);
        }
    </script>

    这里需要注意的是,在script标签中,需要加入th:inline=“javascript”去声明在下面的javascript中使用到了model的内容。

    暂时就先记这么多,需要用的时候,再不定期补充。

  • 相关阅读:
    flink源码阅读(概览)
    idea如何设置home目录
    博客园定制化从入门到精通
    CAP理论的理解
    几个常用的profiler工具对比jprofiler、vituralVM、yourkit、JVM profler
    kafka的使用经验
    netty高并发框架
    Mysql Explain 详解
    show engine innodb status解读
    Class.getResourceAsStream()与ClassLoader.getResourceAsStream()的区别
  • 原文地址:https://www.cnblogs.com/wangxinblog/p/7819048.html
Copyright © 2011-2022 走看看