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



我为电子邮件创建了一个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} 变量?

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

 model.addAttribute("invoiceId", invoiceId); 

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

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

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

最新更新