使用Node.js的SendGrid模板中的变量替换不起作用 [英] Variable substitution in SendGrid templates with Nodejs does not work
问题描述
遵循使用案例在SendGrids上,github确实设法向我发送了带有正确模板的电子邮件,但是替换显然无效,并且在生成的电子邮件中保留为空白.服务器端:
Following the USE CASE on SendGrids github does manage to send me the e-mail with the correct template, but the substitutions does apparently not work, and is left blank in the resulting e-mail. Server side:
const sgmailer = require("@sendgrid/mail");
sgmailer.setApiKey(process.env.SENDGRID_API_KEY);
sgmailer.setSubstitutionWrappers('{{', '}}');
const msg = {
to: '...',
from: 'sender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
templateId: '...',
substitutions: {
name: 'Some One',
city: 'Denver',
},
};
sgmailer.send(msg)
模板中的HTML:
<html>
<head>
<title></title>
</head>
<body>
Hello {{name}},
<br /><br/>
I'm glad you are trying out the template feature!
<br /><br/>
<%body%>
<br /><br/>
I hope you are having a great day in {{city}} :)
<br /><br/>
</body>
</html>
收件箱中显示的电子邮件地址:
Resulting email in my inbox:
你好,
很高兴您正在尝试使用模板功能!
I'm glad you are trying out the template feature!
我希望您在:)过得愉快.
I hope you are having a great day in :)
此处显然缺少变量. 如何正确替换变量?
Here the variables are clearly missing. How do I substitute variables correctly?
推荐答案
由于我使用的是SendGrid中的 dynamic 模板,因此我不能使用"substitutions"标签,而必须使用"dynamic_template_data"标签,请参见此问题.将msg-object更改为
Since what I was using was dynamic templates from SendGrid, I cannot use the "substitutions" tag, but must instead use the "dynamic_template_data" tag, see this issue. When changing the msg-object to
const msg = {
to: '...',
from: 'sender@example.org',
subject: 'Hello world',
text: 'Hello plain world!',
html: '<p>Hello HTML world!</p>',
templateId: '...',
dynamic_template_data: {
name: 'Some One',
city: 'Denver',
},
};
有效.据我所知,这未在SendGrid文档中进行记录.
it works. This is not documented in the SendGrid-documentation as far as I can see.
这篇关于使用Node.js的SendGrid模板中的变量替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!