将代码从变量添加到带有Thymeleaf(Spring)的html头标签中



我有一个用Spring Boot和Thymeleaf编写的Web应用程序。 我需要在 HTML 头标签内动态添加一个自定义"代码"。此自定义"代码"存储在 Spring 模型对象的变量中。我尝试了很多方法,但似乎都没有奏效。这些是我测试的所有方法:

<head>
#1 [[${headCode}]]
#2 <div th:text="${headCode}"></div>
#3 <span th:text="${headCode}"></span>
#4 <div th:html="${headCode}"></div>
#5 <div th:text="${headCode}" th:remove="tag"></div>
#6 <div th:html="${headCode}" th:remove="tag"></div>
#7 <span th:text="${headCode}" th:remove="tag"></span>
</head>

例: 假设我们有这个 Spring 控制器,它将一个特定的代码放在模型变量 "headCode" 中:

@GetMapping
public String getPage(Model model){
String headCode = "<script>
console.log('1');
</script>
<script>
console.log('2');
</script>
<script>
console.log('3');
</script>"
model.addAttribute("headCode", headCode);
return "page";
}

我希望在渲染的 html 页面中拥有这样的东西:

<html>
<head>
[head content]
<script>
console.log('1');
</script>
<script>
console.log('2');
</script>
<script>
console.log('3');
</script>
</head>
<body>
[body content]
</body>
</html>

我没有固定的代码,我无法在头部部分中对其进行硬编码,因此我需要找出一种不同的方法将其插入头部部分。例如,此自定义代码可能是Facebook Pixel,我每次需要时都必须能够更改它。有什么想法吗?

也许您应该尝试使用替换整个标头元素并在片段签名中传递所需的任何变量的片段。

在官方文档中,有一个例子:

https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#parameterizable-fragment-signatures

<header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>

希望这有帮助!

下面是如何使用来自控制器的数据设置端点的工作示例:

@GetMapping(VIEW_NAME)
public ModelAndView viewPage() {
ModelAndView modelAndView = new ModelAndView(VIEW_NAME);
modelAndView.addObject("yourDto", new YourDto());
return modelAndView;
}

您在 HTML 代码中的第二次尝试是正确的,问题应该与您传递给控制器中的视图的字符串有关。 您应该检查百里香叶文档的条件部分 您也可以下载他们的存储库的工作示例。

最新更新