Saw*_*mar 5 javascript template-engine node.js express
MsSql - 2014
我最近开始在 nodeJs 上编程。
我在数据库表中有电子邮件模板。
例如:
message1 : Hello {friendName},
Happy Birthday {friendName}.
Thank you,
{Name}
message2 : Hello All,
The total expense as;
{ListOfExpense}
Thank you,
{Name}
Run Code Online (Sandbox Code Playgroud)
对于消息 1 - 我在输入 obj 上将 UI 输入作为名称和朋友名称。对于消息 2 - 我在 input.expense obj 上有费用列表的 UI 输入。
我可以从 DB 中读取 var dbMessage = message 1 or message 2;
我想使用模板引擎根据模板更改 {} 值并存储在文本中,以便我可以在正文中进行设置。
我正在使用 nodemailer 发送邮件;
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : ? // I want use text as email body.
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
res.end("error");
}else{
res.end("sent");
}
});
Run Code Online (Sandbox Code Playgroud)
请帮忙。
嗯,你可以通过多种方式做到这一点。
您只进行字符串插值,因此您可以非常轻松地使用带有ES6 模板文字的函数..
function myTemplate(env) {
const template = `Hello ${env.friendName},
Happy Birthday ${env.friendName}.
Thank you,
${env.Name}`;
return template.replace(/\n/, '<br>');
}
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : myTemplate({friendName: "foo", Name: "Bar"});
};
Run Code Online (Sandbox Code Playgroud)
您可能想稍微修剪一下,但这将帮助您开始。
其他模板语言包括Pugjs(以前称为 Jade)、Handlebars.js和_.template。通常,这些更专业的第三方模板会编译为 JavaScript 函数,并且它们的调用方式与我们上面的函数相同。所有上述引擎都必须以自己的方式设置......
const pug = require('pug');
const myTemplate = pug.compileFile('myPugPath.pug');
myTemplate({friendName: "foo", Name: "Bar"});
Run Code Online (Sandbox Code Playgroud)
另外,您发送电子邮件与此问题无关。只需以某种方式编写一个 HTML 字符串(例如,使用 ES6 模板文字或 pug),然后发送正确设置 mime 类型 ( text/html) 的电子邮件,并将正文设置为 html。
如果您的数据库中有该模板,那么pug.compileFile您只需使用pug.compile(resultFromDb.pugTemplate). 查看 pug 的文档以获取更多信息。
| 归档时间: |
|
| 查看次数: |
3209 次 |
| 最近记录: |