Wednesday 13 March 2013

Using Jade with ExpressJs for node.Js

This post will give you a very basic information about usage of Jade with Express framework for node.js. After giving a brief introduction about Jade and what it offers we will design a simple page using some of the cool features of Jade. 

What is Jade 

Jade is a high performance template engine for node.js. It offers a wide variety of features to us. --> Jade

What it offers

The default template in ExpressJs is Jade. Jade offers a great alternative to raw Html. The Jade code which we write will inturn be converted to Html by the engine. Some of the cool features in offer include ,


  • Html tags can be avoided.
                 <html>
                      <head>
                         <title>
                                Jade Introduction
                         </title>
                      </head>
                      <body>
                      </body>
                  </html>

              Can be done using,

                   html
                     head
                       title Jade Introduction
                     body 

        How Cool is that !! 
  • Helps us add dynamic content to a page. Objects can be passed to a Jade page which can then be iterated through to display the content. Among the features are Switch Case, Each (for loop) and mixins. Jade Github Page gives you the whole bunch of features that are available in Jade. We will implement some of them.
A Jade Page using Switch and Each 

  • Go to some folder of your liking and type out the following to create a base version of the app.
          express --session --css stylus jadeintro

          This creates our app with sessions enabled, using stylus for css and using Jade. And ofcourse you could see  our app folder as jadeintro.

  • The next step would be to install the dependencies. Get into the folder jadeintro and type out npm install. 
          cd jadeintro
          npm install 
  • You could see that in views/ directory, there are two Jade files. One would be layout.jade and other would be index.jade. Layout contains the main layout of the page that index is going to use. 
  • You could see already that a value is passed to the Jade page that is being displayed as #{title} in index.jade
  • In app.js by default / is directed to routes.index. That is index function exported in index.js file. 
                   app.get('/', routes.index);
           The line says to call routes.index function when a get request for the root page is received. In index exported at index.js file we see just a single line ,

                   res.render('index', { title: 'Express' });
              res.render is calling index , which would call index.jade and it is passed an object title. This title is going to be used in index.jade page.

  • Lets pass something other than the simple title object that is being passed. Lets pass an object which contains a list which we will display in our page.
                    exports.index = function(req, res){
              var obj1 = {
                        key : 'Point 1',
        value : ' Jade is Awesome '
              };
              var obj2 = {
          key : 'Point 2 ',
        value :' Jade is cool '
              };
             var arr = [] ;
             arr.push(obj1);
             arr.push(obj2);
                     res.render('index', {title: 'Express', data: arr});
                  };

  • Lets now modify the index.jade file to print the stuff we just passed to it.
                   extends layout

                   block content
             h1= title
             p Welcome to #{title}
             ul
       each item in data
         li #{item.key} ------------- #{item.value} 
Easily done. Output looks something like this in my chrome browser.



    Well that ends out Jade introduction. Just a quick reminder on how Jade works. Its based on indentation. You can use either spaces or tabs and not both. Mostly we use tabs and its a bit easier that way. But by default it would be using spaces. Change accordingly. Have fun trying out Jade now!! 

Tuesday 12 March 2013

Node.js - A Sample App

I do realize the best way to move forward now is to start creating an app. We learn loads of stuff when we start trying out stuff.

The name of our app is TaskManager. App primarily has two pages .


  • A Login Page 
  • Home Page
Login Page is the starting page of the website and after login user will be redirected to his home page.


Home page will have options to

  • Add a New Task
  • List the Tasks of the user
A sneak peak on how the login screen will look like once we are done,



Prerequisites

  1. Nodejs installed
  2. Express package added
  3. mongodb installed.
  4. A Teeny tiny intro to jade 
  5. And a beginner level intro to stylus
After getting Hello World ready using the way we did in last post, we can now go ahead and start doing the fancy stuff. 

Jade

Jade is a really gud alternative to using html in our code. Apart from giving the basic stuff as in html, Jade can also help add dynamic stuff to the page(which we ll see in our app) . Jade Help

Stylus

Stylus is an alternative to css stylesheet. There is a compiler which inturn converts our stylus code to .css file. An easy alternative to css. 

Mongodb

Mongodb is the database that we are going to use. A very basic introduction to mongodb can be found here

Database Design

Lets create a database in mongodb using ,

                use taskmanager 

Create two collections users and tasks. users will have the information about our users for authentication and tasks , the tasks. 

               db.users.insert({uname:"sherlock" , password:"pass"})

This will create first user entry in db. The structure of tasks is going to be 

              db.tasks.insert({uname:"sherlock", date: "12-03-2013", desc: "desc"})

Exporting index.js : 
  • Now lets get into adding code to perform task whn we enter home page.
  • In app.js add the following 
    •  app.get('/', routes.index) 
      That will call export.index in the routes file where we can handle what needs to be done with our home page.
             exports.index = function (req, res) {
         res.render('index', {title : ""})
             };
      This will inturn render index.jade file. Jade file and its contents can be found in the github code. Please follow it from there. 
       
             Taskmanager Code

      Well we have added code in jade to add the signup button with username and password textboxes added. Now we need to handle what needs to be done when signup is clicked.

     We will add code in app.js to handle post to /signup page.

             app.post('/signup', routes.signup)

     If you take a peak at whats in code from the github link provided you will find that we have processed the  form data passed to signup and checked Db to find if the user is valid .
     If the user details has passed the Authentication test we redirect the user to home page.


Home Page:

   I have not mentioned much about the stylesheet and jade codes for the index page. If you take a peak at the code, you will be able to understand the straightforward code.

   Home page is where we do the core functionality. We provide an option to user to add tasks and we also display the set of tasks added by user. Again a sneak peak at what the output will look like.


There are some sweet code added in home.jade which needs to be highlighted. A cute little feature of jade is that objects can be passed to the jade code. If you take a look at the home.jade code we will see that it uses  the objects that are passed to it and prints the same. 

Using loops in jade

It was a wow moment when i realised that i can loop in jade and print stuff just like you would embed html within php loops. It is used in home.jade code where we pass the objects to jade code. There we use a loop and print all tasks which is how we add the tasks that are in right side of page.

                     block rightcontent
             .widget
      h2 Saved Tasks
      ul
each item in data
li #{item.date} - #{item.desc} <hr/>


A Cool and simple Hack 

Ajax is not being used in this code to avoid complexity for this sample simple website. But when we add task  in the home page we see it immediately without having to refresh manually ( refresh does take place tho) .

We pass the task information to "/posttask" . Code for that is in user.js where you would see this code,
                   
        exports.posttask = function(req, res) {
var databaseUrl = "taskmanager"; // "username:password@example.com/mydb"
var collections = ["users", "tasks"];
var db = require("mongojs").connect(databaseUrl, collections);
// add the task to db and redirect to the /home page . the task list will be updated by then
AddToDb(req, res);
}

Add to db adds stuff to db and redirects us to home page. If you see the home page code, we get tasks from db before displaying them and therefore we have them neatly updated. This sums up our sample app to create the Taskmanager app.

There are loads of stuff from code which i haven't mentioned here. Please take a look at them from the code base in github. TaskManager code . I wouldn't want to make this post any longer. If you dont get the this working you may ask your questions in comments. Hit +1 if you find this useful. Have fun coding !!