简体   繁体   English

Spring 启动,Thymeleaf 和字符串

[英]Spring Boot, Thymeleaf and strings

Hello I'm using spring boot 2.4.x and I want to use thymeleaf as my template engine.您好,我正在使用 spring 启动 2.4.x,我想使用 thymeleaf 作为我的模板引擎。

I've added the thymeleaf starter and I've the following test我添加了 thymeleaf 启动器,并且我进行了以下测试

@Test
void name() {
    StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();

    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addTemplateResolver(stringTemplateResolver);

    Context ctx = new Context();
    ctx.setVariable("franco", "prova");

    String processedTemplate = templateEngine.process("<html>${franco}</html>", ctx);

    Assertions.assertThat(processedTemplate).isEqualTo("<html>prova</html>");
}

but the templateEngine is not substituting the variable and the value of the processedTemplate variable is the same as the input string.但是 templateEngine 没有替换变量,并且 processesTemplate 变量的值与输入字符串相同。

What's my fault?我有什么错? Thank you谢谢

Thymeleaf won't process variables directly in HTML. Thymeleaf 不会直接在 HTML 中处理变量。 You either have to use the text inlining syntax:您要么必须使用文本内联语法:

<html>[[${franco}]]</html>

or do it the standard way (which is to use attributes prefixed with th: ) like this:或者使用标准方式(即使用以th:为前缀的属性),如下所示:

<html th:text="${franco}" />

or或者

<html><span th:text="${franco}" /></html>

(Also, as a side note StringTemplateResolver is the default resolver, so you don't have to configure it. Your complete code can look like this.) (另外,作为旁注, StringTemplateResolver是默认解析器,因此您不必配置它。您的完整代码可能如下所示。)

@Test
void name() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();

    Context ctx = new Context();
    ctx.setVariable("franco", "prova");

    String processedTemplate = templateEngine.process("<html>[[${franco}]]</html>", ctx);
    Assertions.assertThat(processedTemplate).isEqualTo("<html>prova</html>");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM