Thymeleaf常⽤语法:HTML属性设置
使⽤Thymeleaf的属性来设置HTML属性。
(1)使⽤th:attr属性可以修改原来HTML节点的属性;
(2)th:attr属性可以同时设置多个属性;
(3)每⼀个HTML属性都有对应的Thymeleaf属性,如th:attr="value='值'"可换为th:value="值"
(4)HTML的type为checkbox、readonly、required、disabled的,Thymeleaf属性可写为th:checked="true/false"形式;
(5)使⽤th:attrappend和th:attrprepend分别在HTML属性的后⾯或前⾯加⼊数据;
(6)使⽤th:styleappend和th:classappend分别向原有style、class属性添加样式;
(7)HTML5⾃定义属性以“data-”作为前缀,Thymeleaf同样⽀持⾃定义属性,例如可以使⽤“data-th-text”代替 “th:text”,使⽤“data-th-each”代替“th:each”;
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
新建⼀个名称为demo的Spring Boot项⽬。
1、l
加⼊Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、src/main/java/com/example/demo/TestController.java
ample.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
thymepublic class TestController {
@RequestMapping("/")
public String test(){
return "test";
}
}
3、src/main/resources/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:id="form1" th:attr="method='post',action=@{/user/save}">
<input type="text" value="值1" th:value="值2"/>
<input type="text" th:readonly="true"/>
<input type="text" th:disabled="true"/>
<input type="checkbox" th:checked="true"/>
<input type="checkbox" th:checked="false"/>
<div id="div1" th:attrappend="id='-data'" th:styleappend="'color:#ccc'"></div>
<div id="div2" th:attrprepend="id='data-'" class="class1" th:classappend="class2"></div>
<input id="user" type="text" data-person-name="lc" data-age="30"/>
<div data-th-text="hello"></div>
<script>
var obj = ElementById("user");
//获取HTML5属性值的2种⽅式,⽤dataset⽅式时,如果名称带连字符则使⽤时需驼峰化
var s = obj.dataset.personName + "," + Attribute("data-age");
alert(s);
</script>
</form>
</body>
</html>
浏览器访问:localhost:8080
页⾯弹出:lc,30
右键查看⽹页源代码,⽣成的HTML源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="form1" method="post" action="/user/save">
<input type="text" value="值2"/>
<input type="text" readonly="readonly"/>
<input type="text" disabled="disabled"/>
<input type="checkbox" checked="checked"/>
<input type="checkbox"/>
<div id="div1-data" ></div>
<div id="data-div2" class="class1 class2"></div>
<input id="user" type="text" data-person-name="lc" data-age="30"/>
<div>hello</div>
<script>
var obj = ElementById("user");
//获取HTML5属性值的2种⽅式,⽤dataset⽅式时,如果名称带连字符则使⽤时需驼峰化var s = obj.dataset.personName + "," + Attribute("data-age");
alert(s);
</script>
</form>
</body>
</html>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论