How to cache compiled templates of Haml-js in Node.js

I recently came across Node.js technology, which is nothing but JavaScript based event driven server side platform. Further studies made me use Haml-js for templating. As of I studied, using both of them we can make good maintainable and scalable applications.

For improving Haml-js performance, I had to cache the compiled templates on some location or using some mechanism. I used Memcached in Node.js to store compiled templates.

Considering that you already know node.js and haml-js, If not that please first thing is getting installed Node.js and Haml.js on your machines. Steps for Node.js can be follow here and Haml-js can be followed here. Once both of the steps are followed correctly. Have some basic understanding of both with some examples.  Then proceed with below example to see how I implemented memcached templates of haml-js in node.js

We will create new directory for our example as follows:-

Here we can create sample template file as sample.haml with some markup into it.

We will create a JavaScript file mem.js which will store and load compiled template from memcachde and throw the output on HTTP Server. In this first we will load all the modules and connect to memcached server and have some dynamic data.

I have my local memcached setup on 127.0.0.1 on 11211 port. You can replace the values with the ones of yours. Now time comes to create a HTTP server.

Here its very clear that I have just created a HTTP server which prints out text “Open blank test” when you point your browser to http://127.0.0.1:1337/

We will modify these code and render actual template

Now you see actual HTML coming from template and data from data variable. var haml has value from file sample.haml and then in next line we compile the file data and  store in var js. Line below that has Haml.execute function which renders the compiled template. In between of this we will have memcached to store the compile file.

First we try value for var js from memcached whose value is stored in “compiled”. If we find it we use the same, if we don’t find it then we read the sample.haml and compile store in memcached. We close memcached connection as we will further no more use the memcached in the cxample.

You can download the complete example by clicking here.

I will surely update the this blog with more explanations on each of the functions and steps.

Leave a Reply