Node.js and JSON Template : A delicious pairing

I recently blogged about the virtues of Node.js and my personal desire to use JavaScript on the server. Well, I decided to start putting the pieces together. First of all, every good web framework needs a template system. I found JSON Template, a simple enough template system written in JavaScript and intended for client-side HTML template work.

I decided to combine the “Hello, World” examples from Node.js and JSON Template. This is what I came up with.

The first thing you have to do is make JSON Template conform to the CommonJS standard which Node.js so wisely implements. To do that, add the following line to the end of the json-template.js file:

exports.jsontemplate = jsontemplate;

That was easy enough. Put that file in the same folder as your Node.js project and include it with the following line:

var jsontemplate = require("./json-template").jsontemplate;

And now for the big finale, Node.js with JSON Template:

var sys = require("sys");
var http = require("http");
var jsontemplate = require("./json-template").jsontemplate;
 
http.createServer( function (request, response) {
    response.sendHeader(200, {"Content-Type":"text/plain"});
    var t = jsontemplate.Template('Hello {name}');
    var text = t.expand({'name': 'world'});
    response.sendBody(text);
    response.finish();
}).listen(8000);
 
sys.puts("Server running at http://127.0.0.1:8000/");

Thanks to MV for referring me to CommonJS. He seems to have realized the power of an all JavaScript web development stack for some time and has some good rants on the topic.

Comments 2

  1. Stephen Belanger wrote:

    Nice catch! I’ve been tinkering with node.js quite a bit lately and have been trying to decide on a good template engine–this one looks beautiful. It’s just perfect for what I need. :)

    There’s nothing quite so elegant as JSON for passing data around. ;)

    Posted 05 Feb 2010 at 10:33 pm
  2. Steven Roussey wrote:

    There is a CommonJS version of json-template at:

    http://github.com/andychu/json-template

    Posted 19 Feb 2010 at 9:34 am

Post a Comment

Your email is never published nor shared. Required fields are marked *

Powered by WP Hashcash