I am trying to add helper functions to my ejs templates. I have followed the answers provided in the link nodejs ejs helper functions. However it doesn't seem to work. All other properties from the ViewModel
object appears except for the timestamp property, which is passed to the timestamp function in app.locals
.
The object being rendered to the main template
const ViewModel = {
image:{
uniqueId: 1,
title: 'Sample Image 1',
description: 'This is a sample.',
filename: 'sample1.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
},
helpers/timeago.js
const moment = require('moment');
module.exports = (timestamp) => {
return moment(timestamp).startOf('minute').fromNow();
}
Relevant code from server.js
const helpers = require('./helpers');
helpers(app);
helper.js Putting the function into app.locals
const timeago = require('./../helpers/timeago');
module.exports = (app) => {
app.locals.timeago = timeago;
};
Main.ejs template: Using the function in app.locals
<em class="text-muted"><% timeago(image.timestamp) %></em>
How do I successfully add functions to app.locals and use them in an ejs template?