服务器端使用node.js的mustache.js示例

我正在寻找一个与node.js一起使用mustache.js的例子

这是我的例子,但它不工作。 胡子是未定义的。 我正在使用来自主分支的Mustache.js。

var sys = require('sys'); var m = require("./mustache"); var view = { title: "Joe", calc: function() { return 2 + 4; } }; var template = "{{title}} spends {{calc}}"; var html = Mustache().to_html(template, view); sys.puts(html); 

我通过npm安装胡须,使用正确的require语法和(如Derek所说)使用胡子作为对象而不是函数

 npm install mustache 

然后

 var sys = require('sys'); var mustache = require('mustache'); var view = { title: "Joe", calc: function() { return 2 + 4; } }; var template = "{{title}} spends {{calc}}"; var html = mustache.to_html(template, view); sys.puts(html); 

你的例子几乎是正确的。 小胡子是一个对象,不是一个函数,所以它不需要()。 重写为

 var html = Mustache.to_html(template, view); 

会让它更快乐。

感谢Boldr http://boldr.net/create-a-web-app-with-node不得不将下面的代码添加到mustache.js

 for (var name in Mustache) if (Object.prototype.hasOwnProperty.call(Mustache, name)) exports[name] = Mustache[name]; 

不完全确定它在做什么,但它的工作原理。 现在就试着去理解它。

看一看Node.js的简洁介绍

为了解决这个问题,我打开了mustache.js,并在创buildMustache的时候删除了var声明