29

I'm looking for an example using Mustachejs with Nodejs

here is my example but it is not working. Mustache is undefined. I'm using Mustachejs from the master branch.

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);
Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54
onecoder4u
  • 391
  • 1
  • 3
  • 6

4 Answers4

33

I got your example working by installing mustache via npm, using the correct require syntax and (as Derek said) using mustache as an object not a function

npm install mustache

then

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); 
AngusC
  • 628
  • 5
  • 9
18

Your example is almost correct. Mustache is an object, not a function, so it doesn't need the (). Rewritten as

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

will make it happier.

Derek Gathright
  • 741
  • 5
  • 10
10

Thanks to Boldr http://boldr.net/create-a-web-app-with-node Had to add the following code to mustache.js

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

Not exactly sure what it is doing but it works. Will try to understand it now.

August Lilleaas
  • 54,010
  • 13
  • 102
  • 111
onecoder4u
  • 391
  • 1
  • 3
  • 6
  • It basically adds everything in the Mustache object to the [special] exports object. This is necessary as this is how modules work in node.js http://nodejs.org/docs/v0.4.8/api/modules.html#modules – Rajat Jun 02 '11 at 06:37
-2

Take a look to A Gentle Introduction to Node.js

To fix I opened up mustache.js and removed the var declaration when Mustache is being created

Pietro
  • 156
  • 1
  • 4