对电子邮件使用lodash ._模板
问题描述:
我正在尝试使用lodash _.template
创建一个带有Node.js的HTML电子邮件模板。当我使用下面的代码时,出现此错误:((__t = (firstName)) == null ? '' : __t) +
。对电子邮件使用lodash ._模板
有关我在做什么错的任何想法?另外,应该只有一个为所有动态字段编译的模板?
var firstName = _(contactinfo).pluck('firstName');
var compiledFirst = _.template('template with <%= firstName %>!');
var htmlFirst = compiledFirst(firstName);
var lastName = _(contactinfo).pluck('lastName');
var compiledLast = _.template('template with <%= lastName %>!');
var htmlLast = compiledLast(lastName);
var data = {
from: [email protected],
to: email,
subject: 'Your Order Confirmation',
html: '<p>Dear '+ htmlFirst + htmlLast+': '</p><br>
<p>Thank you for your order. . . </p><table><tr>
<thead><th><strong>Items</strong></th></thead></tr></table>'
}
这里是阵列的样子:
[
{
"address": "555 Broadway",
"city": "New York",
"email": "[email protected]",
"firstName": "John",
"lastName": "Doe",
"phone": "2125551212",
"state": {
"code": "NY",
"state": "New York"
},
"value1": true,
"zip": "10001",
"$id": "-K-qmfZzHgQaEM7uHKEK",
}
]
答
注意pluck
返回与firstName
(或选择属性)的数组,数组中的所有对象。不仅如此,但你必须命名模板对象:
var firstName = _(contactinfo).pluck('firstName');
var compiledFirst = _.template('template with <%= firstName %>!');
var htmlFirst = compiledFirst({firstName: firstName[0]});
它可能会更容易只是有一个模板,并通过contactInfo
对象是:
var htmlAll = _.template('<%= firstName %> <%= lastName %>')(contactInfo[0])
请介意这只会获得第0个contactInfo条目。如果你想要不止一个,你可能需要迭代 - 你也可以在lodash模板中做到这一点。
你正在为'lastName'做'pluck('firstName')' –
@Explosion Pills感谢你的指出。修正它上面。 – Ken