【问题标题】:How to use Thymeleaf in html with variable included inside of a h1 tag?如何在 html 中使用 Thymeleaf 并在 h1 标签中包含变量?
【发布时间】:2023-03-21 09:47:01
【问题描述】:

所以我刚开始使用 Thymeleaf,我不确定如何将它与 html 标签一起使用。我搜索了文档,但找不到有关此特定问题的任何信息。看起来很简单,但我无法显示一个 h1 html 标记,其中包含来自我的控制器的变量。

所以我的基本控制器如下所示:

@SpringBootApplication
@Controller
public class HomeController {
    @RequestMapping("/")
    public String index(Model model, @RequestParam(value="name", required=false, defaultValue="Human") String name) {
        model.addAttribute("name", name);
        return "home/index.html";
    }

}

我的 html 看起来像这样:

    <!DOCTYPE html>
<html lang="en">
<head th:replace="fragments::header"></head>
<body>
<h1 th:text="Hello + ${name}"> </h1>
<p>Welcome to Spring Boot!</p>
</body>
</html>

当我加载我的页面时,它看起来像“Helloname”,Hello 和变量名之间没有空格。我怎样才能解决这个问题?我是否以正确的方式使用它?

【问题讨论】:

  • 在单引号中使用文本文字,其中包含空格:&lt;h1 th:text="'Hello ' + ${name}"&gt; &lt;/h1&gt;。这就是 text literalliteral token 之间的区别。可以在here找到一个很好的语法总结。
  • 这能回答你的问题吗? Thymeleaf: Concatenation - Could not parse as expression。不同的答案中显示了各种不同的方法/语法 - 有些可能与您的情况无关,但其他应该是。
  • 如果你正在构建这样的字符串,我推荐literal substitutions&lt;h1 th:text="|Hello ${name}|" /&gt;
  • 谢谢!我真的很喜欢文字替换方法。似乎容易多了。
  • 另请参阅wimdeblauwe.com/blog/2021/01/11/…,了解您拥有的各种选项。

标签: html spring eclipse spring-boot thymeleaf


【解决方案1】:

添加单引号应该可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2018-06-14
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多