Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

8/17/2013

Bootstrap data with Jade templating engine

Jade is templating engine closely related to expressjs. It is not a surprise, since jade is created by a same author. Jade is heavily influenced by syntax of Ruby and Haml.
There are lot of great features in Jade, that makes dealing with compex views on server side really  smooth. One of them is ability to transfer data directly to html ( jade file ), without additional request.
Let me explain that more. We know that HTTP request are expensive. So it is a good pattern to initially load as more content as possible,  so we don't have to make new requests to server. That is  a winning paradigm that  makes single page web applications so powerful on the client side.  On the client, simply load all the view once and make Ajax request for data if needed.  Since Jade is rendered on the server, this approach is especially useful when application needs data from database for the first load.

With Jade we can easily bootstrap data like this:

//
//here data is plain js object
var data = { "name": "myApp","version":0.0.0,"db":"mongodb"};

// now just render existing view, with data object attached   
app.get("/",function(req,res){
    res.render("home",{obj:data}) 
//

In the previous example data object  was local, contained in the same file as main app file. When we want  to bootstrap data from database, we take same approach when rendering jade template.
Again, data is attached to Jade template. The only difference is that we have to have access to database.

Here is example:
//
exports.queryDB = function (req,res) {
    db.collection("jazz",function (err,collection) {
        collection.find().toArray(function (err,collection) {
            res.render("jazz",{giants:collection});
        });
    });
};
//

Database example is a function that asynchronously query data, due to nature af nodejs native mongodb driver. But when we have data, we can manipulate with it with Jade syntax. For example, to iterate over data object and insert it in the html we can do this:

    // 
    ul
        each giant in giants
            li
                a(href="#{giant["name"]}") #{giant["name"]}
    //


Now we have nice list of jazz giants on our page, bootstrapped on first request.

Thanks for visiting my blog.

No comments:

Post a Comment