Thymeleaf 常用语句

Thymeleaf 是一款用于 Java Web 应用的模板引擎,它允许你在 HTML 模板中使用动态内容。以下是 Thymeleaf 中一些常用的语句:

  1. 输出变量值

    <p th:text='${variable}'></p>
    
  2. 条件判断

    <div th:if='${condition}'>
        <!-- 如果condition为true,则显示该div -->
    </div>
    <div th:unless='${condition}'>
        <!-- 如果condition为false,则显示该div -->
    </div>
    
  3. 循环遍历

    <ul>
        <li th:each='item : ${items}' th:text='${item}'></li>
    </ul>
    
  4. 属性赋值

    <img th:attr='src=@{${path} + ${fileName}}, alt=${alt}' />
    
  5. 引入静态资源

    <link rel='stylesheet' type='text/css' th:href='@{/static/css/style.css}' />
    <script type='text/javascript' th:src='@{/static/js/script.js}'></script>
    
  6. 模板继承

    <html th:fragment='html'>
        <head>
            <title>标题</title>
            <meta charset='UTF-8' />
            <link rel='stylesheet' type='text/css' th:href='@{/static/css/style.css}' />
            <script type='text/javascript' th:src='@{/static/js/script.js}'></script>
        </head>
        <body>
            <div th:replace='common/header :: header'></div>
            <div th:replace='${content}'></div>
            <div th:replace='common/footer :: footer'></div>
        </body>
    </html>
    
    <!-- common/header.html -->
    <header th:fragment='header'>
        <!-- 头部内容 -->
    </header>
    
    <!-- common/footer.html -->
    <footer th:fragment='footer'>
        <!-- 底部内容 -->
    </footer>
    
  7. 表单提交

    <form th:action='@{/path}' method='post'>
        <input type='text' th:name='name' th:value='${user.name}' />
        <input type='password' th:name='password' th:value='${user.password}' />
        <input type='submit' value='提交' />
    </form>
    

通过学习这些基本语句,你可以开始使用 Thymeleaf 创建动态网页,并为你的 Java Web 应用增添活力。

Thymeleaf 常用语句 - 快速入门指南

原文地址: https://www.cveoy.top/t/topic/n5eS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录