banner



Handlebars Continue Div Onto Another Page

In this tutorial, we will see how to Create a Website With Express Handlebars – NodeJS. With the handlebar-express, we can create a template to render .hbs template and also we can organize our template in such a way that it can be reusable.

Installing Express Handlebars

In Node js, we can render HTML template but when it comes to the dynamic part i.e we have some data and that must be bind in the template. where else in normal HTML it becomes tricky to bind data so using a Handlebar JS to build semantic templates.
So let's first install the required packages.

bash

                          npm install express express-handlebars --save                      

which will install the two packages.

package.json

                          {   "name": "Node-JS-and-Handlebars",   "version": "1.0.0",   "description": "",   "main": "index.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit 1"   },   "keywords": [],   "author": "",   "license": "ISC",   "dependencies": {     "express": "^4.17.1",     "express-handlebars": "^4.0.4"   } }                      

Folder Structure For App and Express Handlebars Templates

The next step is needed to define a proper folder structure, As in the package documentation the folder structure is mention like this:

App Folder Structure

                          |-- package.json |-- index.js |-- views |   |-- layouts |   |   |-- main.hbs |   | |   |-- partials |   |   |-- header.hbs |   |   |-- footer.hbs |   | |   |-- home.hbs |   |-- about-us.hbs                      

Views

On the app root level, create a folder name views which will contain all the files regarding the template.


Layouts

Inside the views folder, there's will be another folder names as layouts which will contain the index file of the application in which just HTML boilerplate will be added the body content will serve from the views folder's root template files.


Partials

Inside the views folder, there's will be another folder names as partials which will use as a shared template files folder such as header and footer and any other reusable HTML block.

Setup Routes and Template Engine Using Handlebars

At the very first will set our index.js with two basic routes and also will configure the template engine to render or .hbs files.

index.js

                          const express = require('express'); const exphbs = require('express-handlebars'); const app = express();  // Configure template Engine and Main Template File app.engine('hbs', exphbs({     defaultLayout: 'main',     extname: '.hbs' })); // Setting template Engine app.set('view engine', 'hbs');  // routes app.get('/', (req, res) => {     res.render('home'); }); app.get('/about-us', (req, res) => {     res.render('about-us'); });  // port where app is served app.listen(3000, () => {     console.log('The web server has started on port 3000'); });                      

The res.render('home') will render the template name as home.hbs to the assigned route.
Now will setup the template files to make our first index page. so in our views/layouts/ will add HTML boilerplate content to main.hbs file

main.hbs

                          <html lang="en"> <head>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">     <title>Book Face</title> </head>  <body>     <!-- Body Content will render here -->     {{{body}}}      <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> </body> </html>                      

And in the Views folder home.hbs will contain the body part which will render that content into the main.hbs {{{body}}} place

home.hbs

                          <div class="container">  <h1>Hello World from Handlebars</h1>  <p>This is home page</p> </div>                      

This will render the home content to the base route.
Express Handlebars Nodejs
let us see further how can a partials HTML block can be implemented in the template.

Using Shared Partials Handlebars Template

Before we use the partial templates lets first put some content inside the header.hbs to use the same header HTML block in both pages i.e. home and about-us page.
using a simple bootstrap navbar example.

header.hbs

                          <nav class="navbar navbar-expand-lg navbar-light bg-light">   <a class="navbar-brand" href="#">Geekstrick</a>   ...   <div class="collapse navbar-collapse" id="navbarNav">     <ul class="navbar-nav">       <li class="nav-item">         <a class="nav-link" href="/">Home</a>       </li>       <li class="nav-item">         <a class="nav-link" href="/about-us">About us</a>       </li>     </ul>   </div> </nav>                      

And now where ever we want to place the header in pages we just to use the following syntax to render the HTML block.
Syntex: {{ > filename_without_extension }}

home.hbs / about-us.hbs

                          {{> header}} <div class="container">  ... </div> {{> footer}}                      

Bind Data To Template

Using handlebars we can even send the data to the template by just passing the data inside the render method.

index.js

                          ... app.get('/', (req, res) => {     res.render('home', { msg: 'This is home page'}); }); ...                      

Display Data Conditionally

We can use the if-else condition in the template itself to show data conditionally.

home.hbs / about-us.hbs

            ... <p>   {{#if msg}}     {{msg}}   {{else}}     No message was found   {{/if}} </p> ...                      

Display Array Data

Handlebars also allow us to display an array of object data into templates using each syntax.

index.js

                          ... app.get('/people', (req, res) => {     res.render('people', { peoples: [       { name: 'user1'},       { name: 'user2'},     ]}); }); ...                      

people.hbs

            ... <ul class="people_list">   {{#each peoples}}   <li>{{name}}</li>   {{/each}} </ul> ...                      

Helper Methods in Handlebars

handlebars also allow us to create and configure helper methods that can be used in the template. let's consider if we want o display the current date and time zone.
We have to assign the helper method in the app.engine configuration.

index.js

                          ... app.engine('hbs', exphbs({     defaultLayout: 'main',     extname: '.hbs',     helpers: { todaysDate: () => new Date() } })); ...                      

And in the template file, we just have to set the function name which we have defined wherever we want to display.

header.hbs

            ... <div class='date'>   {{todaysDate}} </div> ...                      

in case if the method accepts an argument the syntax would be like.

header.hbs

            ... <div class='date'>   {{todaysDate '12/12/12'}} </div> <!-- Incase multiple arguments --> <div class='date'>   {{todaysDate '12/12/12' 'UTC'}} </div> ...                      

Get More tutorials on Nodejs

  • isaachsenfroutilt.blogspot.com

    Source: https://www.geekstrick.com/create-website-with-handlebars-express-nodejs/

    0 Response to "Handlebars Continue Div Onto Another Page"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel