If else, For Each, Unless, Dynamic Data, layout, Comments with Handlebars Templating in Express.js

Rodrigo Figueroa
Geek Culture

--

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

Initiate the package JSON
Initiate the package JSON

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

Example structure for views and layouts
Example structure for views and layouts

Inside the main layout and the layout2, you need to add all basic HTML structure

Example main basic HTML structure
Example main basic HTML structure
Example layout 2 basic HTML structure adding some info
Example layout 2 basic HTML structure adding some info

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 }` ))
Example basic structure for express server with handlebars
Example basic structure for express server with handlebars

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:

Example running our server and checking the first home page
Example running our server and checking the first home page

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

Example library and funny.js file and directory
Example library and funny.js file and directory
Example adding the fun.handlebars file
Example adding the fun.handlebars file
const RandomNames =['Sarah','August','Via','Jack','Allison','Emos','Julian','Mile']
exports.randomName = () => {return RandomNames[ Math.round( ( Math.random() * RandomNames.length ) + 0 ) ]}
Example exporting random names from our funny.js file
Example exporting random names from our funny.js file
Calling our randomName from our funny.js file
Calling our randomName from our funny.js file
Example using our randomName in fun’s view
Example using our randomName in fun’s view

Run our server and go to http://127.0.0.1:1024/fun, and what will we have?

Example fun page
Example fun page

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

Example adding an object in the response function
Example adding an object in the response object
Example printing the names into the fun handlebars view
Example printing the names into the fun handlebars view

As you see, I added one with two curly brackets and the other with 3, the result is something like this:

Example printing names into the fun’s view and with HTML tags
Example printing names into the fun’s view and with HTML tags

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.

Example adding forIf property to the object and the value to true
Example adding forIf property to the object and the value to true

Then we need to add the if to the handlebars view

Example adding the if to the handlebars view
Example adding the if to the handlebars view

And rerun our server

Example the if on the web page
Example the if on the web page

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.

Example adding comment and the else if we have false as a value
Example adding comment and the else if we have false as a value

Let’s make this works

Changing the forIf value to false
Changing the forIf value to false
Example using the else on the fun page
Example using the else on the fun page

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

Example adding an array to the object
Example adding an array to the object
Adding the each and the unless to the handlebars view
Adding the each and the unless to the handlebars view

Rerun our server

Example fun’s web page
Example fun’s web page

Iterate and print dynamic information but searching the object with {{../}}

Adding users array to iterate
Adding users array to iterate
Adding for each , unless and using the ../ to seek for the forIf value inside of the for each
Adding for each, unless and using the ../ to seek for the forIf value inside of the for each

Rerun our server and we will have something like this

Example fun’s page outcome
Example fun’s page outcome

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

Example layout2 on the layouts directory
Example layout2 on the layouts directory
Example adding the custom layout to our fun view
Example adding the custom layout to our fun view
Example custom layout in the fun’s page
Example custom layout in the fun’s page
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

Sources

--

--

Rodrigo Figueroa
Geek Culture

I’m a Web Developer, fanatic of books and Smash Player.