I would like to separate the template from the data using mustache.js in node… It is not obvious using fs.readFile if this is possible. Any Thoughts?
I’m using data.js as the array model and helloworld.html as the template
var mustache = require('mustache');
var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
console.log('request recieved at ' + (new Date()).getTime());
fs.readFile('./data.js', encoding='utf8',function(err, data) {
model2 = data;
console.log(model2); //logs the data.js as expected
});
fs.readFile('./helloworld.html', function(err, template) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(mustache.to_html(template.toString(),model2)); //model2 is not being passed in
});
}).listen(8081);
You could try using jinjs. It is a port of the Jinja, a very good Python templating system. You can install it with npm like this :
in template.tpl :
in your template.js :
The output will be :