Java 如何向Thymeleaf 3中的片段添加附加内容

Java 如何向Thymeleaf 3中的片段添加附加内容,java,thymeleaf,Java,Thymeleaf,我想使用向片段添加其他内容,但不知道如何添加。例如,我想要一个名为layout的片段,它看起来像: <head th:fragment="head(title)"> <title th:include="${title}">My App: </title> </head> 我可以通过以下方法实现这一点: <head th:fragment="head(title)"> <title th:include="${title

我想使用向片段添加其他内容,但不知道如何添加。例如,我想要一个名为
layout
的片段,它看起来像:

<head th:fragment="head(title)">
  <title th:include="${title}">My App: </title>
</head>
我可以通过以下方法实现这一点:

<head th:fragment="head(title)">
  <title th:include="${title}">My App: <th:block th:include="${title}"></th:block></title>
</head>

我的应用程序:
但是,Thymeleaf不鼓励使用
th:include

th:insert和th:replace(和)之间有什么区别 th:包括,从3.0开始不推荐)


有人能告诉我如何修复我的模板,使其使用最佳实践(如前所述,参考意味着这意味着不使用
th:include
)呈现如上所示吗?

这里的复杂性来自这样一个事实,即您不希望
标记直接进入您的片段(使用
~{::title}
和一个
th:replace
在片段的
标记处)。相反,在这里,正如您所解释的,您实际上是在用包含模板中的文本内容丰富片段的

这里的关键是在标记选择器中使用
/text()
修饰符,这意味着“选择此标记的文本内容”,如:

至于你的片段,在你的例子中,我选择内联,可能是这里最简单的选择:

<head th:fragment="head(title)">
  <title>My App: [[${title}]]</title>
</head>
如果包含的模板可能没有
标记,并且您希望检查这种可能性,如果没有标题发送到片段,则只需使用
我的应用程序
文本作为标题,您也可以使用新的无操作标记(
):


我的应用程序

免责声明,根据StackOverflow规则:我是Thymileaf的项目负责人。

哦,还有一条附加评论:
“head”
可能不是最好的片段名称,因为它可能与
标记冲突。注意标记选择器可以应用于没有任何
th:fragment
属性的片段上…
<head>
    <title>My App: Please Login</title>
</head>
<head th:fragment="head(title)">
  <title th:include="${title}">My App: <th:block th:include="${title}"></th:block></title>
</head>
<head th:include="layout :: head(title=~{::title/text()})">
    <title>Please Login</title>
</head>
<head th:replace="layout :: head(title=~{::title/text()})">
    <title>Please Login</title>
</head>
<head th:fragment="head(title)">
  <title>My App: [[${title}]]</title>
</head>
<head th:fragment="head(title)">
  <title th:text="|My App: ${title}|">My App</title>
</head>
<head th:fragment="head(title)">
  <title th:text="${title} ? |My App: ${title}| : _">My App</title>
</head>