SpringBoot入门——Thymeleaf简单使用

本文只展示代码实现,具体参考此博客实现

举例使用Thymeleaf的:赋值,拼接,if判断,unless判断,for 循环,HTML文本替换

IndexController后台代码


@Controller
public class IndexController {
    /***
     * index页面
     */
    @RequestMapping("/Index")
    public ModelAndView Index(){
        /*for循环*/
        List<UserModel> users= new ArrayList<>();
        UserModel um=new UserModel();
            um.setAge("18");
            um.setName("Howie");
        UserModel um1=new UserModel();
            um1.setAge("20");
            um1.setName("Tang");
        users.add(um);
        users.add(um1);

        Map<String, Object> map=new HashMap<>();
            /*赋值*/
            map.put("description","Hello SpringBoot");
            /*拼接*/
            map.put("joint","Howie");
            /*for循环*/
            map.put("users", users);
            /*if unless判断*/
            map.put("test", "123");
            /*HTML文本替换*/
            map.put("HTML", "<h1>Hello</h1>");
        return new ModelAndView("index","result",map);
    }
}

index页面代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello Index</h1>

    <h2>赋值</h2>
    <p  th:text="${result.description}">description</p>

    <h2>拼接</h2>
    <span th:text="'Welcome,' + ${result.joint} + '!'"></span>

    <h2>for循环</h2>
    <span th:each="nn: ${result.users}">
        年龄:<span th:text="${nn.age}"></span>
        姓名:<span th:text="${nn.name}"></span>
        <br>
    </span>

    <h2>if判断</h2>
        <a href="www.baidu.com " th:if="${result.test =='123'}" ></i>百度</a>
        <a href="www.taobao.com " th:if="${result.test =='1234'}" ></i>淘宝</a>
        <br>

    <h2>unless判断</h2>
        <a href="www.baidu.com " th:Unless="${result.test =='123'}" ></i>百度</a>
        <a href="www.taobao.com " th:Unless="${result.test =='1234'}" ></i>淘宝</a>
        <br>

    <h2>HTML文本替换</h2>
    <span th:utext="${result.HTML}"></span>

</body>
</html>

Usermodel自定义

public class UserModel {
    public String name;
    public String age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }

运行页面效果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值