gpt4 book ai didi

java - 我如何 "add to"一个 Thymeleaf 片段,而不是替换

转载 作者:行者123 更新时间:2023-12-05 00:13:46 28 4
gpt4 key购买 nike

我希望能够使用 thymeleaf 片段,使用其中的所有内容,但有时会从使用它的页面添加额外内容。典型案例:我有一个页脚模板,其中包含我想要在每个页面上使用的脚本引用。在某些页面上,我想添加另一个脚本引用,但不是全部。

我的网络应用程序中有以下设置(降低了复杂性以专注于重点):

layout.html:

<html>
<body>
<div class="container">
<div fragment="content"></div>
</div>
<div th:replace="shared/footer :: footer"></div>
</body>
</html>

共享/footer.html

<html>
<body>
<div th:fragment="footer" th:remove="tag">
<script th:src="{@/scripts/a.js}"></script>
</div>
</body>
</html>

index.html

<html>
<body>
<div th:fragment="content" class="myClass">
<h1>Oh hello</h1>
</div>

<!-- what do i put here?!!! -->
</body>
</html>

我想做的是能够从 index.html 向页脚添加一些额外的内容:

例如:

<div th:addExtraStuff="footer">
<script th:ref="@{scripts/b.js"></script>
</div>

所以最终结果是这样的:

<html>
<body>
<div class="container">
<div class="myClass">
<h1>Oh hello</h1>
</div>
</div>
<div>
<script src="/scripts/a.js"></script>
<script src="/scripts/b.js"></script>
</div>
</body>
</html>

显然 th:addExtraStuff 不存在 - 但你明白了。我想要现有的内容,并且能够提供我自己的内容。我认为如果我将所有可能性都放在片段中然后使用评估来决定是否实际包含该可能性,它会开始变得太复杂。我可能是错的。

最佳答案

我在不使用自定义方言的情况下解决此问题的一种方法是在我用作布局模板的片段上使用参数,我称之为“主布局”。此示例允许您省略不需要覆盖的元素,但您提供的任何元素都将添加到“main-layout”片段中的任何内容中。

基本模板是这样的

主视图.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:fragment="main-layout">
<head>
<title>Template Head Title</title>
<th:block th:replace="${head} ?: ~{}" />
</head>
<body>
<header>
Common Template Header Here
<th:block th:replace="${contentHeader} ?: ~{}" />
</header>
<main>
Common Template Content Here
<th:block th:replace="${content} ?: ~{}" />
</main>
</body>
<footer>
Common Template Footer Here
<th:block th:replace="${footer} ?: ~{}" />
</footer>
</html>

使用它看起来像

<!DOCTYPE HTML>
<html th:replace="main-view.html :: main-layout (head=~{:: head}, contentHeader=~{:: header}, content=~{:: main}, footer=~{:: footer})">
<head th:remove="tag">
<title>Greeting Head</title>
</head>
<body>
<header th:remove="tag">
Greeting Content Header
</header>
<main th:remove="tag">
Greeting Content
</main>
</body>
<footer th:remove="tag">
Greeting Footer
</footer>
</html>

关于java - 我如何 "add to"一个 Thymeleaf 片段,而不是替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com