Forms Using Jade: Node.js

Forms are one of the important components of web application. You need registration form, login form, edit form, status update form etc ..

forms-in-Jade-nodejs

In this video tutorial we shall see how to write the form in Jade, and how to use Twitter Bootstrap to design the form (we just show you how to add the id or class tags and not actual bootstrap implementation – but if you need any help, you can always ask us in the comment section below).

Related Read:
Basics of Jade – Template Engine: Node.js
Loops and Conditions In Jade: Node.js
Mixins in Jade: Node.js

Route To Render Form
app.js

1
2
3
app.get('/edit', function(req, res){
 res.render('edit-form');
});

We define a route /edit and once someone visits this route, we render our edit-form.jade template file.

Form tags in Jade
edit-form.jade

1
2
3
4
5
6
7
8
9
10
form(method="POST", action="/user")
 input(type="hidden", name="_method", value="PUT")
 p Name
  input(type="text", name="name")
 p Email
  input(type="email", name="email")
 p Age
  input(type="number", name="age")
 p
  input(type="submit")

Here we indent input tags inside paragraph tags, which is a child of form. We separate form attributes using comma.

Forms Using Jade: Node.js


[youtube https://www.youtube.com/watch?v=1RC9re_llx0]

YouTube Link: https://www.youtube.com/watch?v=1RC9re_llx0 [Watch the Video In Full Screen.]



Form tags with Jade and Bootstrap
edit-form.jade

1
  input#btn(type="submit")

If you want to use bootstrap along with your jade template files, make sure to include bootstrap.min.css and bootstrap.min.js and jquery.min.js into your file, by opening layout.jade present inside your view folder. Now add the id or class names along with the html tags, this should render you bootstrap enabled functionality and styling.

Form output source code
view-source:localhost:3000/edit

1
2
3
4
5
6
7
<form method="POST" action="/user">
 <input type="hidden" name="_method" value="PUT"/>
 <p>Name<input type="text" name="name"/></p>
 <p>Email<input type="email" name="email"/></p>
 <p>Age<input type="number" name="age"/></p>
 <p><input type="submit"/></p>
</form>

You can observe the nesting of elements and their relationship – child and parent.

Fetch Data From MongoDB: Node.js

What’s the use of the data in database, if we can’t fetch it and display on a web page! Today’s video tutorial concentrates on fetching data out of our mongoDB collection and displaying it on the web page.

fetch-data-from-mongoDB-nodejs

Related Read: Save data To MongoDB: Node.js

Route to display registered users
app.js

1
2
3
4
5
6
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs});
});
});

Once the user visits /view route, she will be presented with all the registered users information. Inside /view route, we fetch all the user information by using mongoDB’s find() method. find() takes 2 parameters – first parameter is an object with condition, second parameter is a callback method. If we pass in empty object as first parameter, it means, fetch all the data – similar to SELECT * in sql.

If find() could successfully fetch the data out of mongoDB collection, it renders index.jade file and passes an object to it – which contains information of all the fetched users.

Template To Display User Information
view/index.jade

1
2
3
ul
each user in users
 li #{user.name}: #{user.age}: #{user._id}

Here we loop through users object, fetch individual user information, and display as a list item.

Fetch Data From MongoDB: Node.js


[youtube https://www.youtube.com/watch?v=U0zK-Nb2vn8]

YouTube Link: https://www.youtube.com/watch?v=U0zK-Nb2vn8 [Watch the Video In Full Screen.]



Note: Since email address has been made as _id, each registered user will have a unique email address associated with her.

Fetch individual user information
app.js

1
2
3
4
5
6
app.get('/view', function(req, res){
user.find({_id: '[email protected]'}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs});
});
});

Observe the find() methods first parameter. Now we are passing _id to it, which means, it has to find and retrieve only the information related to the user with that _id.

Full Code To Insert And Fetch Data into/from MongoDB
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
mongoose.connect('mongodb://localhost/Company');
 
var Schema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', Schema);
 
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else    res.render('index', {users: docs});
});
});
 
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.redirect('/view');
});
});
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

To make this work, go to Save data To MongoDB: Node.js tutorial page and copy the index.html page code and create one for your project and put it inside public directory. Now you can directly access root(html form), enter user information and submit, which redirects to /view route, wherein you get the information of all the registered users.

Note: Make sure MongoDB server is running and turned on, when you start Node.js server and access your application from web browser.

Related Read: MongoDB – Getting Started Guide

Basics of Jade – Template Engine: Node.js

Lets learn some of the basics of Jade Template Engine. Jade is the default template engine for Express Web Framework of Node.js Also note that, Jade and Express are open source product of the same company, so go very well with each other!

jade-template-engine-nodejs-express-web-framework

Using template engine might seem pointless in the beginning, but if you’re building a large-scale application, it’s a handy tool and you’ll feel good about your decision to use one for your project.

Make sure you’ve installed Express Web framework and Jade module locally for your application. You can find the procedure at Express Web Framework: Node.js

Configuration Section
app.js

1
app.set('view engine', 'jade');

This would let your application know that you’ll be using Jade as Template Engine. This way, you need not mention the Template Engines file extension each time.

Jade File: Indentation
index.jade

1
2
3
4
html
 head
  title Technotip
 body

Would output

1
2
3
4
5
<html>
 <head><title>Technotip</title></head>
 <body>
 </body>
</html>

Indentations in Jade decide which element(s) is/are a child off which element.

Jade File: Variable
index.jade

1
2
 - var name = "Love For Design"
 p= name

and

Jade File: String. Minus sign significance
index.jade

1
2
 - var name = "Love For Design"
 p #{name}

Out put Love For Design on the browser, inside a paragraph tag.

Jade File: Code Interpretation – REPL
index.jade

1
 p #{ 1 + 5 }

This outputs 6 on to the browser inside a paragraph tag.

Jade File: String Length Management
index.jade

1
2
3
4
5
6
7
 p
  | My Name is Satish
  | I Love web development
  | I love helping people
  | by teaching them whatever I know
  | I believe, this is a good cause of 
  | spreading knowledge.

This would treat the entire string as a single line text, and out put looks like:
My Name is Satish I Love web development I love helping people by teaching them whatever I know I believe, this is a good cause of spreading knowledge.

Jade File: Id’s and Classes
index.jade

1
2
div#wrapper
  p.highlight I Love Node.js

This would apply the id wrapper to div and highlight class to p tag.

Jade File: Multiple id and class
index.jade

1
2
div#wrapper.content.highlight
  p I Love Node.js

We could even assign multiple id’s and classes to a html element.

Jade File: Anchor Tag
index.jade

1
a(href="/about", rel="nofollow") Satish

This would wrap the word Satish with anchor tag and nofollow attribute.

Jade File: Anchor Tag and Image Tag
index.jade

1
2
a(href="/about", rel="nofollow") Satish
img(src="1.gif", alt="Child Eating KitKat")

This would output Satish with anchor tag and nofollow attribute. Also an image with alt attribute attached to it. Both these tags are siblings.

Jade File: Hyperlink the Image file – Hypermedia
index.jade

1
2
a(href="/about", rel="nofollow")
 img(src="1.gif", alt="Child Eating KitKat")

Indent img tag inside anchor tag and the image gets linked to by the anchor tag.

Jade File: Writing Function inside Jade file
index.jade

1
2
- var fn = function() { return "android KitKat"}
p #{fn()}

This outputs android KitKat to the browser.

Jade File: Accessing elements of Object
index.jade

1
2
3
4
- obj = { name: "Apple", product: "iPhone"}
ul
  li #{obj.name}
  li #{obj.product}

This would output

  • Apple
  • iPhone

Jade File: Accessing elements of an array
index.jade

1
2
3
4
- obj = [ "Nexus 5", "iPhone 5S"]
ul
  li #{obj[0]}
  li #{obj[1]}

This would output

  • Nexus 5
  • iPhone 5S

Jade File: Including another jade file
index.jade

1
2
p
 include show

This would include the contents of show.jade file inside index.jade file.

Basics of Jade – Template Engine: Node.js


[youtube https://www.youtube.com/watch?v=xNoWTLsZbaU]

YouTube Link: https://www.youtube.com/watch?v=xNoWTLsZbaU [Watch the Video In Full Screen.]



Note:
sign tells jade that the code that follows should be executed.
= sign tells that the code should be evaluated, escaped and then output.

Stay subscribed: In next video we’ll show how to use bootstrap + Express + Jade + Node.js
Building a web form. Loops and Conditional statements present in Jade.

Express Web Framework: Node.js

In this video tutorial we shall briefly look at Express web framework for Node.js

express-modules-file-structure-nodejs

With today’s tutorial we will be discussing the basics of Express and we’ll also be running a small example application built with Express, also we shall have a first look at Jade Template Engine.

REPL
global installation of Express Framework

C:\>npm install -g express

This installs the express globally, so that you can access it from anywhere in the system.

Also note that, you’ll need internet connection to download and install these packages.

REPL
creating express example application

C:\>cd node
C:\node>express express_example

This creates a folder and some recommended folder structure. If you’re a total beginner to Express Framework, then it’s better to stick on with these folder structure.

Now open the package.json present inside express_example folder
JSON File
package.json

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*"
  }
}

It looks as shown above. It has 2 dependencies: express and jade. Install these dependencies from your command prompt / console.

REPL
installing dependencies

C:\>cd node
C:\node>cd express_example
C:\node\express_example>nmp install

This would install both express and jade, and another folder called node_modules gets created inside express_example folder.


 express-jade-modules-nodejs

Video Tutorials: Getting Started With Express Web Framework: Node.js


[youtube https://www.youtube.com/watch?v=CagrpUlQtdQ]

YouTube Link: https://www.youtube.com/watch?v=CagrpUlQtdQ [Watch the Video In Full Screen.]



Jade File
Jade to HTML

extends layout

block content
  h1= title
  p Welcome to #{title}

This jade file is present inside view folder.

jade-to-html-express-node

More about Jade Template Engine in coming videos ..

Note:


express-modules-file-structure-nodejs

Inside node_modules folder we have dependency modules.
Inside public folder javascript files, css files, images etc are present. Logical part of the application will be kept separate for security reasons.
Inside routes, routing configuration is present.
Inside views, the presentation part of the application is present. If Template Engine is used, those files will be present in this folder. Example: .jade files

app.js Starting point of execution.
package.json Contains app name, version, author, dependency module names etc.

Info: There are many popular websites built upon Express Framework, one that you might know is, MySpace!