Jade node template engine with expressJs example
Here in this post i am going to talk about Jade node template engine with express framework.
This post will show you some basics of using jade template engine in expressJs.
What is Jade Template Engine?
Jade is a very powerful template engine to design UI part of your nodejs application. It is easy to use and you can decrease your dynamic UI development effort instead of rendering core HTML design.
So lets start the tutorial.
First of all you need to setup your node application. Here i am going to use express framework to design my application with jade template engine, So install express using express generator tool and generate skeleton application.
Follow below link to install express in your system.
http://www.iamrohit.in/how-to-install-express-using-express-generator-tool/
Your application directory structure will look like.
Now open views/layout.jade file this is your main layout file you can write here your common header and footer code.
views/layout.jade
doctype html html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body block content |
In above code title= title means
1st is you can use htmlTagName = YourCustomVariable.
2nd is you can use htmlTagName #{YourCustomVariable}
You can also write title #{title} both will work same.
You can pass your html tag properties like this
link(rel='stylesheet', href='/stylesheets/style.css') |
Other example to display input box
input(type="email", name="email", required="required") |
Output will be:
<input type="email" required="required" name="email"> |
Now time to display your dynamic server value on client.
Open file routes/index.js you’ll see
routes/index.js
var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.render('index', { title: 'Home Page'}); }); module.exports = router; |
Open file view/index.jade you’ll see
view/index.jade
extends layout block content h1= title |
Where extends layout importing your layout code on view page, you have to use extends YourlayoutName to import your layout code on each page and you can also create different different layouts for your views.
Where h1= title title is coming from your index.js routing file. you can set more variables to render on view page like
res.render('index', { title: 'Home Page', message:'Hello, I am Home Page', posts:[ {heading:'Heading-1', description:'My First Post'}, {heading:'Heading-2', description:'My Second Post'} ]}); |
View page will be.
extends layout block content h1= title p= message each value in posts value.heading value.description |
Read more about jade template engine http://jade-lang.com/reference/
You can see live working demo of file uploading in nodejs with progress bar using jade template engine by clicking on demo button or read this full post from here http://www.iamrohit.in/file-upload-in-nodejs-with-progress-bar/