In this article, I am going to create a Nodejs express sample app using the jade template engine. Jade is a template engine of Node.js. Template engine helps us to create an HTML template with minimal code. Also, it can inject data into the HTML template at the client-side and produce the final HTML. Vash, Ejs, Mustache, Dust are the other popular template engines available for Node.js.
Jade is a template engine for Node.js. Jade syntax is easy to learn. It uses whitespace and indentation as a part of the syntax.
At first create Nodejs app for creating a server, For that we need to create package.json file first. Create a folder named 'nodejs-with-jade'. After navigating to this folder over terminal run below command to create package.json file
npm init --yes
With above command, package.json file is created with default configuration.
All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies.
Install express and jade NPM packages. Run below command for the same.
npm install express jade --save
This is the first file where the request comes from the frontend/client. create this file with touch server.js and put below code inside it.
In the above file, Below is done
1. Express is imported and app is create using express.
2. views folder is made public so that the template files stored inside will be available to browser.
3. Node.js view engine is set to jade
4. Two get routes is created to show two different pages, home and about us on the browser.
5. App started on port 3000
create a folder name views, then create layout.jade file under the view folder.
The next file inside the template folder is home.jade, Put below code inside home.jade.
The last file is about-us.jade, Put below code inside about-us.jade
Note: Jade uses whitespaces and indentation to define nesting of tags. So the indentation and whitespaces play a crucial role in Jade. So tags should be proper indented otherwise the app will throw an error.
Run below command to run the app.
node server.js
Now check the app on browser. It will look like below:
Using the template engine with Node.js is quite easy. The template engine maximizes client-side processing and it is very useful when we are working on a Node.js application and we want a few pages to host on the application.
You can also find other demos of Other Sample Application here to start working on enterprise-level applications.
Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!
Find complete source code over GitHub