我爱编程

thymeleaf(二) ___ 资源文件引入和引入代码片段

2018-06-03  本文已影响0人  蜗牛船长

html中如何引入css或者js

比如我们需要引入jquey和bootstrap,资源文件结构


image.png

页面中使用@默认从static下面寻找资源文件.
html,其中src路径在我们不启动服务的时候,直接通过src可以访问到资源文件,当启动服务的时候模板引擎将th:ref的属性替换掉默认的ref属性

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
 <link rel="stylesheet" type="text/css" media="all"
          href="../../static/plugins/bootstrap/css/bootstrap.css" th:href="@{/plugins/bootstrap/css/bootstrap.css}" />
</head>
<body>
<table class="table">
    <tr>
        <td class="active">测试1</td>
        <td class="success">测试2</td>
        <td class="warning">测试3</td>
        <td class="danger">测试4</td>
        <td class="info">测试5</td>
    </tr>
</table>
</body>
<script  type="application/javascript"  th:src="@{/plugins/jquery/jquery-3.3.1.min.js}"  src="../../static/plugins/jquery/jquery-3.3.1.min.js"  ></script>
<script  type="application/javascript"  th:src="@{/plugins/bootstrap/js/bootstrap.js}"  src="../../static/plugins/bootstrap/js/bootstrap.js"></script>
<script type="application/javascript">
    $(function(){
        console.log($);
    })
</script>
</html>

获取contentpath

如果有contentpath,需要加上项目名字的时候,应该怎么获取

 <span th:text="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort()  + #request.getContextPath() + '/'} "
               id="contextPath"></span>

thymeleaf中支持多种内置对象,比如

欢迎您<span th:text="${#session.getAttribute('loginUser')}"></span>

页面跳转路径需要这样写

  <a href="" th:href="${#httpServletRequest.getContextPath()+'/test'}">跳转</a>

引入公共代码片段

比如我们希望引入一个页面的头部或者尾部的公共部分
首先在需要引入的html片段定义一个名称

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>common</title>
</head>
<body>
<div th:fragment="nav"  class="navbar navbar-default navbar-static-top">
       公共部分的html片段,名称为nav
   </div>

页面中去引入此片段,使用th:insert 或者th:replace均可,insert唯一的区别是插入宿主片段中,而replace是替换掉宿主的片段.

 欢迎您<span th:text="${#session.getAttribute('loginUser')}"></span>
    <br/>
    <div th:insert="~{common/common :: nav}"></div>
    <table class="table">
        <tr>
            <td class="active">测试1</td>
            <td class="success">测试2</td>
            <td class="warning">测试3</td>
            <td class="danger">测试4</td>
            <td class="info">测试5</td>
        </tr>
    </table>
image.png

用法

片段引入还有其他的写法,可以不定义片段直接使用选择器的方式
比如在common中同样有这样的一个代码片段,但是没有定义却有id

<div id="footer" >
        &copy; 2018 今天天气还不错
</div>

那么可以这样引用

//代表从common/common 的页面中,寻找Id 为footer的字段
<div th:replace="~{common/common :: #footer}"></div>
上一篇 下一篇

猜你喜欢

热点阅读