如何使用传递给模板的参数在百里香中创建URL?

时间:2019-06-12 10:18:55

标签: 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}变量?

1 个答案:

答案 0 :(得分:1)

通常,您使用模型来通信控制器和视图(我假设您已使用Spring MVC,因为您已经在使用Spring Boot)。唯一的区别是

 model.addAttribute("invoiceId", invoiceId); 

无论您如何交流信息,生成URL时都应使用url templates。这些以@开头,通常允许您移动应用程序而不必在任何地方硬编码其地址:

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

请注意thymeleaf如何处理这些参数:您在网址模板中使用占位符,例如{foo}{bar},然后在末尾用(foo=${baz},bar=${quux})解释它们的含义, ${}中表达式的内容可以是百里香叶可以解释的任何内容。