java - 如何使用传递给模板的参数在 thymeleaf 中创建 URL?

标签 java spring spring-boot templates thymeleaf

我已经为电子邮件创建了一个 html 模板。

现在,我将一个变量放入上下文中:

context.setVariable("invoiceId", invoiceId);

在模板中我有一个标签:

<p><span>To accept the invoice, click <a th:href="http://localhost/accept/${invoiceId}">HERE</a></span></p>

但是当我运行应用程序时,我得到:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "http://localhost/accept/${invoiceId}" (template: "mailTemplate" - line 7, col 47)

在这种情况下如何使用 ${invoiceId} 变量?

最佳答案

通常,您使用模型来通信 Controller 和 View (我假设您使用 Spring MVC,因为您已经在使用 Spring Boot)。这里唯一的区别是

 model.addAttribute("invoiceId", invoiceId); 

无论您如何传达信息,您都应该使用 url templates生成 url 时。这些以 @ 开头,通常允许您的应用程序移动,而无需在任何地方对其地址进行硬编码:

 <a th:href="@{/accept/{id}(id=${invoiceId})}">link text</a>

注意 thymeleaf 如何处理这些参数:您在 url 模板中使用占位符,例如 {foo}{bar},然后在最后解释它们的含义,类似于 (foo=${baz},bar=${quux}),其中 ${} 内表达式的内容可以是 thymeleaf 中的任何内容可以解释。

关于java - 如何使用传递给模板的参数在 thymeleaf 中创建 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56559819/

相关文章:

java - 如何将一系列整数从一个微服务发送到另一个微服务

java - 无法将组件添加到布局

java - shouldoverrideurlloading 的中断函数?

java - 当使用 char 键存储整数时,最好使用什么映射实现?

spring - 执行器刷新未提交的本地文件更改

java - spring 与 javax servlet 的兼容性

spring - 以下属性是如何解析的 ${sys :foo} by Log4j2

java - 为什么将变量声明为 int 类型需要转换流? long 类型不需要强制转换

java - 传递给持久化的分离实体 : com. carpooling.entity.Role;嵌套异常是 org.hibernate

java - spring boot 出现此错误 : The dependencies of some of the beans in the application context form a cycle: