ejs + express.js with global template variables
express, web, view, render
Using ejs as template-engine within express.js default configuration can be very annoying – you have to pass a dedicated variable set to each response.render() call. But for a lot of tasks it is required to use some kind of global variables in your templates, e.g. page title, resources and much more.
The most reliable solution is a custom template renderer which invokes ejs in the way you want.
Custom Template Engine/Renderer Function#
const _ejs = require('ejs');
// example: global config
const _config = require('../config.json');
// custom ejs render function
module.exports = function render(filename, payload={}, cb){
// some default page vars
payload.page = payload.page || {};
payload.page.slogan = payload.page.slogan || _config.slogan;
payload.page.title = payload.page.title || _config.title;
payload.page.brandname = payload.page.brandname || _config.name;
// resources
payload.resources = payload.resources || {};
// render file
// you can also pass some ejs lowlevel options
_ejs.renderFile(filename, payload, {
}, cb);
}
Usage#
const _express = require('express');
const _webapp = _express();
const _path = require('path');
const _tplengine = require('./my-template-engine');
// set the view engine to ejs
_webapp.set('views', _path.join(__dirname, '../views'));
_webapp.engine('ejs', _tplengine);
_webapp.set('view engine', 'ejs');
// your controller
_webapp.get('/', function(req, res){
// render the view using additional variables
res.render('myview', {
x: 1,
y: 2
});
});