ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 384 forks source link

How to get reference to Handlebars engine from Express middleware #256

Closed mdstiller closed 5 years ago

mdstiller commented 5 years ago

I am trying to create an express middleware function in an external file that will allow me to dynamically load templates based on the route being rendered. Unfortunately, I can't seem to figure out how to get a reference to the Handlebars object that I initially registered as my rendering engine. I was hoping to leverage the req.app functionality of Express to somehow pull this value into my code but so far I'm stuck.

In the code snippet below, the handlebarsEngine object is the object I'd like to return from my req.app object.

`"use strict"

//NPM Includes const fs = require("fs"); const path = require("path");

// Middleware to expose the app's shared templates to the client-side of the app // for pages which need them. let exposeTemplates = (req, res, next) => {

console.log("Middleware:", "exposeTemplates");
var templateDir = path.join(__dirname, "../views/client-templates");
console.log("Extension Name:", handlebarsEngine.extname);

// Uses the `ExpressHandlebars` instance to get the get the **precompiled**
// templates which will be shared with the client-side of the app. 
handlebarsEngine.getTemplates(templateDir, { precompiled: true })
    .then(function (templates) {

        console.log("Reached THEN Statement");`
UziTech commented 5 years ago

you can save the handlebars instance (documentation):

var exphbs  = require('express-handlebars');
app.handlebarsEngine = exphbs.create({ /* config */ });
app.engine('handlebars', app.handlebarsEngine.engine);
app.set('view engine', 'handlebars');

then in your middleware use req.app.handlebarsEngine

mdstiller commented 5 years ago

I was beating my head against a desk about this for awhile so I appreciate the help!