If else, For Each, Unless, Dynamic Data, layout, Comments with Handlebars Templating in Express.js
Hi again and Happy new Year!! I was busy with all the parties, and all the relatives that have been visiting me, and finally I come with some good information about Handlebars templating, the if and the for each and some tips.
Create a directory
I have created a directory called handlebarsprc and inside you need to create the package JSON
Initiate NPM
We need to initiate the package JSON we need to run this command
npm init -y
And it will create the Package JSON when we can install packages
Installing Express and Express-handlebars
You have to Install Express and Express-handlebars with this commands
npm i --save-dev express express-handlebars
Views and layouts structure
Because we are going to use the views and layouts, we should add those directories and adding the views and layouts for instance the home, 404, 500, and on the other hand the layout’s part main and the layout2
Inside the main layout and the layout2, you need to add all basic HTML structure
If you see closely, I added the {{{body}}} this is for the express-handlebars to send all the info from the views.
Create our server
To create our server, it is really important to create a file called project_handlebars.js and add the basic structure to run the server on the port 1024 and on the localhost http://127.0.0.1:1024, the basic code is shared below.
const express = require( 'express' ),
app = express(),
port = process.env.PORT || 1024,
{ engine } = require( 'express-handlebars' )
app.disable( 'x-powered-by' )
app.engine( 'handlebars', engine({
defaultLayout: 'main'}))app.set( 'view engine', 'handlebars' )
app.get( '/', ( req, res ) => res.render( 'home' ))
app.use( ( req, res ) => res.status( 404 ).render( '404' ) )
app.use( ( err, req, res, next ) => res.status( 500 ).render( '500' ))
app.listen( port, console.log( `http://127.0.0.1:${ port }` ))
We started with requiring the express library and save it in a variable called express and initiating the express server and save it in an app variable second we need to save the port in a port’s variable third we need to call the library express-handlebars and with curly brackets take the engine, this is for 6.0.2 version then we disable the x-powered-by for security and after that we can set the engine in this case handlebars and the engine function, we need to pass an object as a parameter, and we can add the default layout as main (the layout that we have created) then we set the default view as view engine and handlebars.
Later we need to create the renders, for now we have one the home, the 404 and the 500, and finally we initiate the listen function with two parameters the first one is the port and the second one is the console.log to show where our server is running for requests.
If we run our server, we will see something like this:
Let’s have some fun
Ok let’s create a directory call lib and inside we can add a funny.js file within that file a function that return random names, let’s create a new view called fun.handlebars also adding as a view in our project_handlebars.js
const RandomNames =['Sarah','August','Via','Jack','Allison','Emos','Julian','Mile']
exports.randomName = () => {return RandomNames[ Math.round( ( Math.random() * RandomNames.length ) + 0 ) ]}
Run our server and go to http://127.0.0.1:1024/fun, and what will we have?
Nothing hahahaha
We will add dynamic data, if else, for each and a different layout to our new fun handlebars file.
To add random names we need to pass the variable as an object in the project_handlebars.js and to implement it is to add {{}} or {{{}}} curly brackets to our fun’s view three is because we want to add HTML5 tags to it
As you see, I added one with two curly brackets and the other with 3, the result is something like this:
Let’s use the if inside handlebars, first of all we need to add {{#if key}} and {{/if }}to close the if, but the key is the variable that we will pass from our object in this case will be forIf the value will be true.
Then we need to add the if to the handlebars view
And rerun our server
Let’s add the else and a comment, for comments you need to add the ! inside the curly brackets {{! comment }} and then we will add the else, you should add inside the if to work properly.
Let’s make this works
Adding the For each and the unless
For the for each we just use the {{#each key}} {{/each}} and for unless {{#unless key}} {{/unless}}
For each do an iteration for the array and we need to add the {{.}} for every value on the array, the unless show something if the key is false
Rerun our server
Iterate and print dynamic information but searching the object with {{../}}
Rerun our server and we will have something like this
Adding a custom layout, in this case you must insert the layout property inside the object that we want to pass to the view and the name of the custom layout
const express = require( 'express' ),
app = express(),
port = process.env.PORT || 1024,
{ engine } = require( 'express-handlebars' ),
{ randomName } = require( './lib/funny.js' )
app.disable( 'x-powered-by' )
app.engine( 'handlebars', engine({
defaultLayout: 'main'
}))
app.set( 'view engine', 'handlebars' )
app.get( '/', ( req, res ) => res.render( 'home' ))
app.get( '/fun', ( req, res ) => res.render( 'fun', {
firstName: randomName(),
firstNameHTML: `<em>${ randomName() }<em>`,
forIf: false,ages: [1,2,3,4,53,4,3,4,3,3323,23,2,5,23,2,5,6],
users: [{ userName: 'Finn', age: 16 },{ userName: 'Marceline', age: 30000 },{ userName: 'Jake the Dog', age: 28 }],layout: 'layout2'} ))app.use( ( req, res ) => res.status( 404 ).render( '404' ) )app.use( ( err, req, res, next ) => res.status( 500 ).render( '500' ))app.listen( port, console.log( `http://127.0.0.1:${ port }` ))
Complete code for fun’s
<h2>Random names</h2>
<h3> Your name is {{ firstName }}</h3>
<h3> Your name is {{{ firstNameHTML }}}</h3>
{{#if forIf}}
<h2>The if is working</h2>
{{! Comment }}
{{else}}
<h3>The else is working</h3>
{{/if}}
<ul>
{{#each ages }}
<li>{{ . }}</li>
{{/each}}
</ul>
{{#unless forIf}}
<h2>Unless</h2>
{{/unless}}
{{#each users}}
<h2>
My name is {{ userName }}
and I'm {{ age }}
and I am a
{{#unless ../forIf }}
Hero
{{/unless }}
</h2>
{{/each}}
Conclusion
In conclusion, we have that we wanted the if, the else, the for each, the unless the comments and to seek for the right property’s object