百里香叶不会取代变量

Dmy*_*kyi 1 java thymeleaf

我是百老汇的新手,很抱歉,如果这是一个虚假的问题.我想用thymeleaf 3创建一个'hello world'.我必须使用存储在数据库中的模板进行操作,我只能将它们作为文本.

我已经读过我需要使用StringTemplateResolver才能实现这一点.

我做了一个例子,但它没有替换我的变量$ {user},我不明白我在哪里弄错了.

// define TemplateEngine
TemplateEngine templateEngine = new TemplateEngine();
StringTemplateResolver templateResolver = new StringTemplateResolver();
templateEngine.setTemplateResolver(templateResolver);

String htmlTemplate = "<b>${user}</b>";
Context context = new Context();
context.setVariable("user", "Ray Donovan");

String res = templateEngine.process(htmlTemplate, context);
System.out.println(res); // it prints out: <b>${user}</b>
Run Code Online (Sandbox Code Playgroud)

有人可以向我强调一下吗?

提前致谢.

ara*_*oid 6

官方文件中报道了Thymeleaf#text-inlining:

[[...]]之间的表达式被认为是Thymeleaf中的表达式内联,在其中您可以使用在th:text属性中也有效的任何类型的表达式.

这么说,你必须使用双方括号表示法.而不是<b>${user}</b>你应该使用<b>[[${user}]]</b>.


Abd*_*han 5

您可以参考@araknoids答案或更新您htmlTemplate

String htmlTemplate = "<b th:text="${user}"></b>";
Run Code Online (Sandbox Code Playgroud)