Loops and Conditions In Jade: Node.js

After going through the basics of Jade, lets learn about loops and conditional statements in Jade.

loops-and-conditions-in-jade-nodejs

Note: Since most text editors designed for web remove the indentation(and some retain only new line characters), thus compressing the file and optimizing it for the web use. But this doesn’t serve any good for writing Jade. Because indentation is at the heart of Jade syntax!

So in this tutorial, we are using a Chrome extension called Jade Editor to illustrate loops and conditional statements. You can simply test your code in this Google Chrome extension and then copy over the code to your actual file. This would even help reduce the complicated errors in lengthy files.

each loop in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
each name in names
  li #{name}

output

  • Apple
  • Microsoft
  • Oracle

sign is optional for each loop. Here it loops through the array names and prints out each element of the array.

each loop and loop index in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
each name, i in names
  li #{i+1}: #{name}

output

  • 1: Apple
  • 2: Microsoft
  • 3: Oracle

This prints out name along with the index number. Since index in JavaScript array starts with 0, we add 1 to it, to make it more sensible for non-programmers.

for loop and loop index in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
for name, i in names
  li #{i+1}: #{name}

output

  • 1: Apple
  • 2: Microsoft
  • 3: Oracle

Same holds good even for for loop.

each loop in Jade
objects: Key, Value pair

1
2
3
4
5
- obj = {cmp1: "Apple", cmp2: "IBM"};
 
ul
each val, key in obj
  li #{key}: #{val}

output

  • cmp1: Apple
  • cmp2: IBM

Since objects in JavaScript has {key: value} pair, we make use of it to extract and print from the object.

for loop in Jade
objects: Key, Value pair

1
2
3
4
5
- obj = {cmp1: "Apple", cmp2: "IBM"};
 
ul
for val, key in obj
  li #{key}: #{val}

output

  • cmp1: Apple
  • cmp2: IBM

Same holds good to for loop too.

Conditional Statements

if, else if, else In Jade
Conditional Statements

1
2
3
4
5
6
7
8
- var fc = 2;
 
if( fc === 0 )
 p You have no followers
else if( fc === 1 )
 p You have 1 follower
else
 p You have #{fc} followers

output
You have 2 followers

Here we use the condition to check for execution of block of code. Also note that sign before if, else if and else keywords are optional.

Loops and Conditions In Jade: Node.js


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

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



In coming video tutorials, we shall learn about Mixins.

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!

External Module( NPM ) Install, Update, Remove: Node.js

This video tutorial illustrates searching, installing, updating and removing the external, free modules.

External Free Node Modules are listed at npmjs.org and is managed by NPMNode Package Manager.

There are so many amazing modules already written to handle so many sophisticated functionalities, that it becomes easy to use them in our application and build a robust, scalable application quickly.

Command to look at all the external module names and their respective description

1
npm search

It gives a long list of names and descriptions.

To make is look better, you can use GREP(if you’re on Linux or Unix based System)
Search with GREP

1
npm search | grep module_name

npm search followed by pipe symbol, which is followed by any module name.

For Windows users

1
npm search module_name

it gives all the details of available methods, properties and their description.

Installation of Modules

init command

1
npm init

Once you run this command, it prompts you with some optional things, like, name of the project, version, author, licensing etc. Once you’re done with that, it creates package.json file with all the details you provided.

The ‘init’ command in NPM allows us to identify our project and list out any Node Modules it requires.

Now open that package.json file: it looks somewhat like this
package.json file

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

You need to open this package.json file using a plain text editor and add your project dependencies i.e., some of the modules you need to install for your project.

In this video tutorial we’re installing 3 external modules:
express
jade
mongoose

package.json file, after editing

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
 "dependencies": { "express": "2.5.8", "jade": "0.26.1", "mongoose": "2.6.5" },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

Now you’ve specified all the external modules your project depends on.

Now using install command, we need to install these modules.
installation command

1
npm install

Once this command is executed, it looks through the package.json file and installs all the dependency modules one by one.

External Module Install, Update, Remove via NPM: Node.js


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

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



What is a module?
A module is a self-contained series of one or more javascript files represented by an object.

Update Command

1
npm update

once you run this command, package.json file is parsed and the dependency modules are checked for any updates, if any, it’ll be updated.
If any module is installed with -g (global scope), i.e., the root installation, then while updating or removing them, it may throw some errors, in such case, use sudo keyword:

Update Command

1
sudo npm update -g

This would solve the problem both for updating and deleting external modules.

remove/delete module command

1
npm prune

To remove the unused modules: open package.json file and remove the module names which you want to remove. Save the package.json file and then run above(npm prune) command. This would safely remove the modules you no more intend to use in your project.

List Global module: using command

1
npm -g ls

This lists all the global modules, it’s path and file structure: as shown below:

Example output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
C:\node\express_example>npm  -g ls
C:\Users\Satish\AppData\Roaming\npm
└─┬ [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    └── [email protected]

Removing/Uninstalling Global modules: using command

1
npm -g rm

This removes all the global modules installed.

Clear cache

1
npm cache clear

After modifiying things from command prompt, if it’s still not working, try clearing the cache.

Note:
To install latest version of the module: you’ll need to write * (asterisk or star) in the place of version number inside package.json file.