Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thymeleaf does not replace variables

Tags:

java

thymeleaf

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.

like image 372
Dmytro Pastovenskyi Avatar asked Oct 16 '25 23:10

Dmytro Pastovenskyi


2 Answers

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

like image 136
araknoid Avatar answered Oct 18 '25 13:10

araknoid


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

String htmlTemplate = "<b th:text="${user}"></b>";
like image 21
Abdullah Khan Avatar answered Oct 18 '25 14:10

Abdullah Khan