2015-10-06 72 views
2

我正在尝试使用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", 
    } 
    ] 
+0

你正在为'lastName'做'pluck('firstName')' –

+0

@Explosion Pills感谢你的指出。修正它上面。 – Ken

回答

1

注意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模板中做到这一点。

+0

如果我打算使用'var htmlAll',我会像第一行那样定义firstName和lastName吗? – Ken

+0

@Ken第二个例子你不需要 –

+0

OK。我试过并定义了'var contactinfo = req.body [0];'但是我得到了一个'无法读取属性'0'的未定义错误 – Ken