2016-12-04 22 views
1

我有一組數據,我想在使用NodeMailer表發送看起來像:解析數據數組並使用nodemailer發送數據?

var results = [ { 
    asin: 'B01571L1Z4', 
    url: 'domain.com', 
    favourite: false, 
    createdAt: 2016-11-18T19:08:41.662Z, 
    updatedAt: 2016-11-18T19:08:41.662Z, 
    id: '582f51b94581a7f21a884f40' 
    }, 
    { 
    asin: 'B01IM0K0R2', 
    url: 'domain2.com', 
    favourite: false, 
    createdAt: 2016-11-16T17:56:21.696Z, 
    updatedAt: 2016-11-16T17:56:21.696Z, 
    id: 'B01IM0K0R2' 
    }] 

什麼,我試圖做我創造我的HTML內循環,然後遍歷數據。我確實嘗試了下面的內容,但似乎我能做的事情有限制。

var sendUpdatedMerch = transporter.templateSender({ 
     from: '"Test" <[email protected]>', // sender address 
     subject: 'Test Updates', // Subject line 
     html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>{{result.forEach((item) => {<tr><td>{{asin}}</a></td><td>{{url}</td><td>{{favourite}}</td><td>{{createdAt}}</td></tr>})}}</tbody></table></div>' // html body 
    }); 

    sendUpdatedMerch({ 
    to: '[email protected]' 
    }, {results}, function(err, info){ 
    if(err){ 
     console.log(err); 
    } else { 
     console.log('Done'); 
    } 
    }) 

任何人都可以指出我要去哪裏錯了,我需要做什麼來糾正我的問題。

回答

1

看起來你已經試過使用results.forEach((item),但你把它放在引號'result.forEach((item)'這是一個字符串,根本不會執行。

您可能使用這種語法在你的頁面,當你使用的視圖引擎,如jadeswig等,這將做解析爲您服務。但是在這裏,你應該手動調用它們來解析這種語法。

否則,你可以用下面的數組函數進行解析,我已經使用了array.reduce這很方便,並且會很好地解析。

您可以嘗試相同的方式生成content並將其附加到html中,如下所示。

html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + 
content + '</tbody></table></div>' // html body 

var results = [ { 
 
    asin: 'B01571L1Z4', 
 
    url: 'domain.com', 
 
    favourite: false, 
 
    createdAt: '2016-11-18T19:08:41.662Z', 
 
    updatedAt: '2016-11-18T19:08:41.662Z', 
 
    id: '582f51b94581a7f21a884f40' 
 
    }, 
 
    { 
 
    asin: 'B01IM0K0R2', 
 
    url: 'domain2.com', 
 
    favourite: false, 
 
    createdAt: '2016-11-16T17:56:21.696Z', 
 
    updatedAt: '2016-11-16T17:56:21.696Z', 
 
    id: 'B01IM0K0R2' 
 
    }]; 
 

 
var content = results.reduce(function(a, b) { 
 
    return a + '<tr><td>' + b.asin + '</a></td><td>' + b.url + '</td><td>' + b.favourite + '</td><td>' + b.reatedAt + '</td></tr>'; 
 
}, ''); 
 

 
console.log(content); 
 

 
/* 
 
var sendUpdatedMerch = transporter.templateSender({ 
 
     from: '"Test" <[email protected]>', // sender address 
 
     subject: 'Test Updates', // Subject line 
 
     html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + content + '</tbody></table></div>' // html body 
 
    }); 
 

 

 
    sendUpdatedMerch({ 
 
    to: '[email protected]' 
 
    }, {results}, function(err, info){ 
 
    if(err){ 
 
     console.log(err); 
 
    } else { 
 
     console.log('Done'); 
 
    } 
 
    }) 
 
    
 
    */

+0

當然唉唉,我不使用模板!這很好。謝謝! – K20GH

+0

@ K20GH偉大:-) – Aruna