为什么“ href”和“ th:href”同时存在?

时间:2019-02-10 10:07:11

标签: thymeleaf

我正在使用Thymeleaf阅读页面。

在“编辑页面”中,有一个“返回”按钮,用于返回到“用户列表页面”。对我来说奇怪的是,此按钮同时具有“ href”和“ th:href”。 image detail of the button

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>user</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">
<br/>
<h1>修改用户</h1>
<br/><br/>
<div class="with:80%">
    <form class="form-horizontal"   th:action="@{/edit}" th:object="${user}"  method="post">
        <input type="hidden" name="id" th:value="*{id}" />
        <div class="form-group">
            <label for="userName" class="col-sm-2 control-label">userName</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="userName"  id="userName" th:value="*{userName}" placeholder="userName"/>
            </div>
        </div>
        <div class="form-group">
            <label for="password" class="col-sm-2 control-label" >Password</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" name="password" id="password"  th:value="*{password}" placeholder="Password"/>
            </div>
        </div>
        <div class="form-group">
            <label for="age" class="col-sm-2 control-label">age</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="age"  id="age" th:value="*{age}" placeholder="age"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="Submit" class="btn btn-info" />
                &nbsp; &nbsp; &nbsp;
                <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
            </div>

        </div>
    </form>
</div>
</body>
</html>

很明显,“ th:href”是用于返回的。关于“ href”属性的功能有何选择?

1 个答案:

答案 0 :(得分:0)

ThymeLeaf的设计目的是使用与您可以在浏览器中查看的原型相同的文件以及可工作的模板文件。实际上,这意味着如果需要,您可以在浏览器中打开模板文件而无需实际运行它,而且看起来还可以。例如,在此代码中:

<a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>

如果直接在浏览器中打开文件,浏览器将忽略th:href(因为它不知道如何处理文件),而是使用href="/toAdd"。但是,当您通过服务器上的模板引擎运行它时,href="/toAdd"被动态表达式th:href="@{/list}"的结果替换。

使用表格更容易显示。像这样:

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>

在浏览器中打开该表格时,您会看到一个表格,其中只有一行(洋葱,2.41,是)。但是,当您通过服务器运行它时,表的实际内容将替换为${prods}变量中存在的任何数据。

相关问题