【问题标题】:Unable to set variables in a Thymeleaf template无法在 Thymeleaf 模板中设置变量
【发布时间】:2017-12-13 16:35:39
【问题描述】:

我正在使用带有一些模板的 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>

添加如下内容确实有效.. 我看到很多人使用标准大括号表示法没有问题,并且想知道什么地方合适。

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    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}"/>
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2020-10-17
      • 2018-12-02
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多