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

one*_*r4u 28 serverside-javascript node.js

我使用的是寻找一个例子MustachejsNodejs

这是我的例子,但它不起作用.Mustache未定义.我正在使用主分支中的Mustachejs.

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);
Run Code Online (Sandbox Code Playgroud)

Ang*_*usC 32

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

npm install mustache
Run Code Online (Sandbox Code Playgroud)

然后

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); 
Run Code Online (Sandbox Code Playgroud)


Der*_*ght 18

你的例子几乎是正确的.Mustache是​​一个对象,而不是一个函数,所以它不需要().改写为

var html = Mustache.to_html(template, view);
Run Code Online (Sandbox Code Playgroud)

会让它更快乐.


one*_*r4u 10

感谢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];
Run Code Online (Sandbox Code Playgroud)

不完全确定它在做什么,但它的工作原理.现在会尝试理解它.