我想使用Thymeleaf选择片段内子元素的位置,如以下示例所示。

Fragments.html:

<div th:fragment="awesomeFragment">
     Some Text
     <div><!-- children must be here --></div>
</div>


view.html:

<div th:replace="fragments :: awesomeFragment">
     <a href="www.google.com"/>
</div>


预期产量:

<div>
     Some Text
     <div><a href="www.google.com"/></div>
</div>


可能吗?如果是这样,我该怎么做?

最佳答案

您可以通过布局来完成。
为此使用Thymeleaf Layout Dialect
(如果使用Spring Boot,则它已打开!)

布局将以以下形式呈现:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title></title>
</head>
<body>
    <header>
        Some text
    </header>
    <div layout:fragment="content">
        <p>Page content goes here</p>
    </div>
</body>




您的页面将是:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
  layout:decorator="base/test">
<head>
    <title></title>
</head>
<body>
    <div layout:fragment="content">
        <a href="www.test.com">Test.com</a>
    </div>
</body>




我在Thymeleaf测试项目中尝试过。浏览器中页面的源代码原来是您想要的:

java - 如何选择 Thymeleaf 片段内子元素的位置?-LMLPHP

10-07 19:33
查看更多