Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

thymeleaf does not replace variables

I'm new to thymeleaf so sorry if it's dummy question. I would like to create a 'hello world' with thymeleaf 3. I would have to operate with templates which are stored in database and I only can get them as a text.

I have read that I need to use StringTemplateResolver in order to achieve that.

I made an example but it does not replace my variable ${user} and I do not understand where I have made mistake.

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

Could somebody highlight that to me?

Thanks in advance.

Upvotes: 4

Views: 7098

Answers (2)

You can refer to @araknoids answer or update your htmlTemplate to

String htmlTemplate = "<b th:text="${user}"></b>";

Upvotes: 6

araknoid
araknoid

Reputation: 3125

Reported in the official documentantion Thymeleaf #text-inlining:

Expressions between [[...]] are considered expression inlining in Thymeleaf, and in them you can use any kind of expression that would also be valid in a th:text attribute.

Said so, you have to use the double square bracket notation. Instead of <b>${user}</b> you should use <b>[[${user}]]</b>.

Upvotes: 17

Related Questions