java - 无法在 Thymeleaf 模板中设置变量

标签 java spring-boot thymeleaf

我使用 Spring Boot 和一些模板来帮助生成一些动态电子邮件。不幸的是,模板引擎没有渲染我的变量。

后端调用

public String generateProblemOfTheDay(Model model) throws IOException {

    Context ctx = new Context();
    ctx.setVariable("potd", "Test Value");

    //Process the template with the proper context variables
    String html = templateEngine.process("index", ctx);
    PrintWriter pWriter = new PrintWriter(Paths.PROBLEM_OF_THE_DAY_OUTPUT, "UTF-8");
    pWriter.println(html);
    pWriter.close();
    log.info("done!");
    log.info(html);

    return html;
}

我的模板片段

.
.
<tr>
    <td style="font-family:'Open Sans', Arial, sans-serif; font-size:15px; line-height:18px; color:#30373b;">
        <br />
        <div class="question-description">
            [[${potd}]]
        </div>
    </td>
</tr>
.
.

我不确定为什么模板引擎无法正确处理变量。这是添加变量的最佳方式吗?

我发现的确实有效

<label style="font-size: 12px;padding-bottom: 1em;" th:text="${potd}">Test</label>

添加类似以下内容确实有效。我看到很多人使用标准大括号表示法没有问题,并且想知道什么在哪里合适。

最佳答案

Inlined expressions were changed from thymeleaf 2 to 3 。我猜你正在使用 thymeleaf 2,这意味着你需要 attribute th:inline="text" in order to get your expression to work .

<div class="question-description" th:inline="text">
    [[${potd}]]
</div>

如果您升级到 thymeleaf 3,这些表达式将开箱即用(它甚至建议您删除 th:inline="text")。至于你应该以哪种方式编写表达式......这几乎是基于意见的。大多数情况下,我喜欢直接在标签中使用 th:text。如果要将很多字符串附加在一起,则可以使用其他方法。例如:

<span>Your answer was: [[${answer}]]</span>

更容易阅读

<span th:text="${'Your answer was:' + answer}"/>

关于java - 无法在 Thymeleaf 模板中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47798066/

相关文章:

java - Spring @EnableRetry 抛出 InternalAutoProxyCreator

java - 如何在 thymeleaf th :if 中使用多个条件(和、或)

java - HashMap 用于类,而不是对象

Java Servlet if 语句不需要 { } 括号?

java - 在并行流上传播 Sleuth baggage

java - Spring Boot : error =“invalid_grant” , error_description =“Bad credentials”

java - 创建名为 'requestMappingHandlerMapping' 的 bean 时出错 - SpringBoot

java - 尝试在 Thymeleaf/Spring MVC 中创建删除按钮

java - Spring boot + Thymeleaf - 编辑时 id 为 null 的对象

java - 加点机制麻烦?