Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass values to variables of a HTML template using Thymeleaf in Spring Boot

I'm setting up an API to send e-mails. I am using the template engine from Thymeleaf to format the body of my e-mail.

I am unable to pass a value to variables in my HTML file.

I have tried using the setVariable function.

Context context = new Context();

//context.setVariable("variable in html", "value to it");// set like this

context.setVariable("name", "ajay");
context.setVariable("date", "23rdfeb");
context.setVariable("rupee", 399);
String sendDay1Email = templateEngine.process("lifecyclemailer/sample", context);

oMessage.get().setText(sendDay1Email, true);

E-mail template:

Dear `${name}`, your pack will expire on `${date}` of `${rupee}`.

This is the e-mail I am supposed to be receiving.

E-mail template:

Dear Ajay, your pack will expire on 23rd Feb of 2019.

This is the e-mail I am expecting.

like image 548
Himanshu Pandey Avatar asked Dec 28 '25 16:12

Himanshu Pandey


1 Answers

In general, Thymeleaf expressions are only processed in HTML tag attributes (like <span th:text="${name}" />) or inlined expressions (like [[${name}]]). Your template probably needs to look like this:

E-mail template:

Dear [[${name}]], your pack will be expired on [[${date}]] of [[${rupee}]].

(This is affected by how you've configured your template engine, but I think inlined expressions work in all modes.)

like image 50
Metroids Avatar answered Dec 31 '25 14:12

Metroids



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!