【问题标题】:Render a variable as HTML in Java Spring Thymeleaf在 Java Spring Thymeleaf 中将变量呈现为 HTML
【发布时间】:2020-10-30 08:49:40
【问题描述】:

在我的 .java 文件中,我有

@RequestMapping(value = "/page1", method = RequestMethod.GET)
public String callback(@RequestParam(name = "token") String token, Model model){
    //do something with token
    //result variable is either 
    //"<p style=\"color:red;font-size:20px\"><strong>fail</strong></p>" 
    //or 
    //"<p style=\"color:green;font-size:20px\"><strong>pass</strong></p>"
    model.addAttribute("result", result);
    return "page1";

在我的 page1.html 文件中:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Page1</title>
</head>
<body>
<p th:text="'here is the result: ' + ${result}"></p>
</body>
</html>

现在,我的 page1 显示:

here is the result: <p style="color:green;font-size:20px"><strong>pass</strong></p>

是否可以将我的结果变量呈现为 html,以便我的 page1 显示一个大的绿色通道?除了 th:text + ${var} 还有其他格式选项吗?我使用的是 spring boot 和 thymeleaf。我试图不为此使用 javascript。

类似 this 的东西,但用于 java

【问题讨论】:

    标签: java html spring-boot model-view-controller thymeleaf


    【解决方案1】:

    这是控制器级别的表示和语义的不良混合,以及 HTML 级别的内容和样式的不良混合。相反,请为 result 使用布尔属性并使用 th:if 或类似属性来切换模板中的 HTML 内容,并避免使用内联样式以支持 class="success" 之类的内容。

    【讨论】:

      【解决方案2】:

      使用这个:

      th:utext="'here is the result: ' + ${result}"
      

      【讨论】:

        猜你喜欢
        • 2012-05-06
        • 2019-06-25
        • 2017-05-15
        • 2012-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多