Having a Node.JS Express template engine with multiple templates in one file


I wrote a custom template engine to let me use my old templates in a rewrite of my current project. Everything is working except that Express.js always sends a

Error: Failed to lookup view (template name)

I have multiple templates in one file and I don't need one file for each template. But how can I tell that to Express?

I can't get my head around this. Any help is appreciated

EDIT: Some Code:

My Express Setup: (app.js)

var express = require('express');
var app = express();
var gclosure = require('./templateEngine');
var fs = require('fs');

 * Setup Express

    app.engine('test', gclosure.__express);

    app.set('views', __dirname + '/public/templates');
    app.set('view engine', 'test');


        src: __dirname + '/public'

    app.use(express.static(__dirname + '/public'));

My Custom Template Engine (templateEngine.js)

exports.renderFile =  function(path, options, fn){

  if ('function' == typeof options) {
    fn = options, options = {};

  try {

    fm(null, "This is a test output");

  } catch (err) {

My test route in express:

  app.get('/', function(req, res, next) {

              title: 'Sources',
              data: 'lala',
              options: 'miep'


The Clue is: When I create a file named simple.test in the template folder everything is working and I can see the test output string. When I change the name to something that doesn't exist the out put is

Error: Failed to lookup view (template name)
Problem courtesy of: Johnnycube


The problem:

Express uses the template engine to create a view object which renders the view. Since the view itself is created by looking up the file into the filesystem the template engine has no way of telling express that it handles the files on its own.

The Solution:

Instead of using a template engine approach I wrote a custom middle-ware that intercepts calls to my template engine depending on the name of the template function. Basically I overwrite the response.render() function in express.

Update: GitHub Repo

Solution courtesy of: Johnnycube


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.