开发者

Separating data from views with mustache.js in node

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 :

npm install jinjs

in template.tpl :

I say : "{{ sentence }}"

in your template.js :

jinjs = require('jinjs');
jinjs.registerExtension('.tpl');
tpl = require('./template');
str = tpl.render ({sentence : 'Hello, World!'});
console.log(str);

The output will be :

I say : "Hello, World!"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜