分享

thymeleaf基础语法及内置对象

 码农9527 2021-08-10

在上一篇中已经讲解了thymeleaf的应用,下面再来介绍一下thymeleaf基础语法及内置对象与工具类。  

thymeleaf基础语法  

thymeleaf基础语法主要有以下四种:  

变量表达式${}  

选择变量表达式*{}  

链接表达式@{}(不安全)  

其他表达式(字符串连接、数学运算、布尔逻辑、三目运算)  

变量表达式${}  

<!-- 变量表达式  -->
<div th:text="变量表达式"></div>
<form id="from">
 <input id="id" name="ID" th:value="${pets[0].id}"/>
 <input id="name" name="名称" th:value="${pets[0].name}"/>
 <input id="varieties" name="种类" th:value="${pets[0].varieties}"/>
</form>1234567复制代码类型:[java]

使用th:value="${pets[0].xx}将pets集合中第一个元素的id/name/varieties属性获取到:  

thymeleaf基础语法及内置对象

选择变量表达式*{}  

<!-- 选择变量表达式  -->
<div th:text="选择变量表达式"></div>
<form id="form" th:object="${pets[0]}">
 <input id="id" name="id" th:value="*{id}"/>
 <input id="name" name="名称" th:value="*{name}"/>
 <input id="varieties" name="种类" th:value="*{varieties}"/>
</form>1234567复制代码类型:[java]

通过th:object="${pets[0]}选取到pets集合中第一个元素,再通过th:value="*{xx}"获取第一个元素的id/name/varieties属性:  

thymeleaf基础语法及内置对象

链接表达式@{}(不安全)  

链接表达式能够直接拿到应用路径并拼接静态资源路径。  

<!--<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">-->
 <link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}">12复制代码类型:[java]

将之前的代码进行了改写,运行代码,F12检查浏览器,会发现这种写法会将webjars版本号泄露出来,所以不建议使用:  

thymeleaf基础语法及内置对象

其他表达式(字符串连接、数学运算、布尔逻辑、三目运算)

<!-- 其他表达式  -->
<div th:text="其他表达式"></div>
<div th:text="${'My name is '+(pets[0].name!=null?pets[0].name:'no name')}"></div>
<form id="from">
 <input id="id" name="ID" th:value="${pets[0].id}"/>
 <input id="name" name="名称" th:value="${pets[0].name}"/>
 <input id="c" name="种类" th:value="${pets[0].varieties}"/>
</form>12345678复制代码类型:[java]

与Java语法基本一致,如果所选宠物刚好没有名字,则显示noname:  

thymeleaf基础语法及内置对象

条件判断  

条件判断通常写法:  

<!--取正-->  

th:if="${articles}"  

<!--取反-->  

th:if="!${articles}"/th:unless="${articles}"  

<div th:if="${pets}">
 <p>找到了一只小畜生</p>
</div>

<div th:if="!${articles}">
 <p>找不到这只小畜生</p>
</div>

<div th:unless="${articles}">
 <p>找不到这只小畜生</p>
</div>1234567891011复制代码类型:[java]

内置对象  

${#ctx}是一个模板引擎的全局上下文对象,可以用来获取其它内置对象

${#locale}

全局上下文中区域语言设置对象
${#param}全局上下文中参数变量
${#request}HttpServletRequest对象(在web环境下使用)
${#response}HttpServletResponse对象(在web环境下使用)
${#session}HttpSession对象(在web环境下使用)
${#servletContext}ServletContext对象(在web环境下使用)

基础对象:  

thymeleaf工具类官方文档  

https://www./doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects  

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多