简体   繁体   English

如何在 Spring Boot 中使用 Thymeleaf 将值传递给 HTML 模板的变量

[英]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.我正在设置一个 API 来发送电子邮件。 I am using the template engine from Thymeleaf to format the body of my e-mail.我正在使用 Thymeleaf 的模板引擎来格式化我的电子邮件正文。

I am unable to pass a value to variables in my HTML file.我无法将值传递给 HTML 文件中的变量。

I have tried using the setVariable function.我曾尝试使用setVariable函数。

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.这是我期待的电子邮件。

In general, Thymeleaf expressions are only processed in HTML tag attributes (like <span th:text="${name}" /> ) or inlined expressions (like [[${name}]] ).通常,Thymeleaf 表达式仅在 HTML 标记属性(如<span th:text="${name}" /> )或内联表达式(如[[${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.) (这受您如何配置模板引擎的影响,但我认为内联表达式适用于所有模式。)

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

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