节点js +模板替换内容

时间:2016-02-06 06:28:10

标签: javascript node.js

我正在努力为员工提供录取通知书。所以我有一些默认模板index.html:

的index.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="header">
<h1>Offer Letter</h1>
</div>

<div id="name">
 Hello [[Name]],

Welcome to our organization,'

Details:

[[Date]]    : Offer Letter Date
[[Name]]    : Employee Name
[[Designation]] : Designation
[[Address]] : Communication Address
[[CTC]]  : Cost to the Company

</div>

<div id="footer">
Copyright
</div>

</body>
</html>

我会在超过300次的时间内生成多个优惠。

所以我有这样的json数据:

var obj = [
 { "name" : "Abc",
  "Date" : "12-12-2014",
  "Designation" : "Admin",
  "Address" : "XXXX",
  "CTC" : 3333},
{ "name" : "wefrwe",
  "Date" : "12-12-2014",
  "Designation" : "Admin",
  "Address" : "XXXX",
  "CTC" : 55},
{ "name" : "dssd",
  "Date" : "12-12-2015",
  "Designation" : "Admin",
  "Address" : "XXXX",
  "CTC" : 333},
{ "name" : "gfsc",
  "Date" : "12-1-2014",
  "Designation" : "Admin",
  "Address" : "XXXX",
  "CTC" : 22},
{ "name" : "dssdds",
  "Date" : "1-12-2014",
  "Designation" : "Admin",
  "Address" : "XXXX",
  "CTC" : 4334}
];

如何将值(例如[[Name]]替换为Abc)。

有任何节点包吗?

我尝试了以下代码,但不知道这是最好的方法和有用的方法。

for(i in obj) {


var textbody = '<!DOCTYPE html> <html> <head> </head> <body> <div id="header"> <h1>Offer Letter</h1> </div> <div id="name"> Hello [[name]], Welcome to our organization,' Details: [[Date]] : Offer Letter Date [[Name]]    : Employee Name [[Designation]] : Designation [[Address]]   : Communication Address [[CTC]]  : Cost to the Company </div> <div id="footer"> Copyright </div> </body> </html>';


textbody = textbody.replace(/{[^{{}}]+}/g, function(key){
    return obj[key.replace(/[{{}}]+/g, "")] || "";
});

}

2 个答案:

答案 0 :(得分:0)

请参阅此节点,以便使用node,nodemailer&amp;玉

How to send an html page as email in nodejs

您的玉石模板应与(

)相似(或更好)
doctype html
html
    head
    body
        p
            | Hello #{newemp.name},
            br
            br
            | Welcome to our organization.
            br
            br
            | Details:
            br
            | #{newemp.Date}  : Offer Letter Date
            br
            | #{newemp.name}  : Employee Name
            br
            | #{newemp.Designation}  : Designation
            br
            | #{newemp.Address}  : Communication Address
            br
            | #{newemp.CTC}  : Cost to the Company

在引用的链接中,您需要传递上下文:

var context = { 
                 "name" : "Abc",
                 "Date" : "12-12-2014",
                 "Designation" : "Admin",
                 "Address" : "XXXX",
                 "CTC" : 3333
              };

为了简单起见,我使用一个员工对象对上下文变量进行了编码,您需要为每封电子邮件动态传递每个员工对象。

答案 1 :(得分:0)

mustache.js是JavaScript中的胡子模板系统的零依赖实现。

Mustache是一种无逻辑模板语法。它可以用于HTML,配置文件,源代码-任何东西。它通过使用散列或对象中提供的值在模板中扩展标签来工作。