Global helpers

First, let's create a global helper that will be available to every Handlebars template we render. The global helper that we will create will be used to format a timestamp so that it is worded according to how long ago the event occurred. We will use this throughout our application for things such as comments and image timestamps.

The first thing we need to do is update our server/configure.js module, where we originally configured Handlebars as our rendering engine. We will add the following section to define our helpers:

app.engine('Handlebars', exphbs.create({ 
    defaultLayout: 'main', 
    layoutsDir: app.get('views') + '/layouts', 
    partialsDir: [app.get('views') + '/partials'], 
    helpers: { 
        timeago: (timestamp)=> { 
            return moment(timestamp).startOf('minute').fromNow(); 
        } 
    } 
}).engine); 

As you can see from the additional code we added (highlighted in the preceding code), we defined the helpers property of the configuration options within create(). Inside the helpers property, we can define any number of functions we want. In this case, we defined a simple timeago function that actually uses another npm module called moment. The moment module is a great library for performing numerous different types of date string formatting. As we are using a new module, we need to be sure to perform require() at the top of our configure module:

const path = require('path'), 
    routes = require('./routes'), 
    exphbs = require('express-Handlebars'), 
    bodyParser = require('body-parser'), 
    cookieParser = require('cookie-parser'), 
    morgan = require('morgan'), 
    methodOverride = require('method-override'), 
    errorHandler = require('errorhandler'), 
    moment = require('moment'); 

Also, we need to actually install it via npm:

    $ npm install moment --save
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.124