Azrael_404
Azrael_404

Reputation: 446

Correct way to initialise variables in HTML

I've a mail template in a .html file. This mail will be sent by a node.js server, so I can't use DOM. The template is loaded like that :

fs.readFile('./ressources/template.html', function (err, html) {
if (err) {
    throw err; 
}   
var templateHTML = html ;

I'm looking for a proper way to pass kind of variables to the html , as the customer name / date / order id.

Have you any idea of a correct practice to do it ?

Upvotes: 2

Views: 70

Answers (1)

dtouch3d
dtouch3d

Reputation: 143

You need a template engine, like Handlebars.

Basic example:

var Handlebars = require('handlebars');

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
             "{{kids.length}} kids:</p>" +
             "<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
             "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);

Would render:

<p>Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:</p> 
<ul> 
   <li>Jimmy is 12</li> 
   <li>Sally is 4</li> 
</ul> 

Upvotes: 3

Related Questions