1

I have created a function to register a new partial with handlebars. I don't want to have everything stuffed inside the same file, so I am using module exports to export the function.

home.js - Used to render views

var fs = require('fs');
var Handlebars = require('hbs');

// Directories, Files and other Variables
var viewsDir = __dirname + '/../views';

// Function Helpers
var renderHtml = require('./helpers/render_html')(fs, viewsDir);

exports.index = function(req, res) {

    renderHtml('main', 'head');
    renderHtml('main', 'body');

    res.render('layout', {
        blogTitle: "My Website",
        blogDescription: "Hello! This is a description :)"
    });
};

render_html.js - The function to register a handlebars partial

module.exports = function(fs, viewsDir) {
    var renderHtml = function(file, section) {
        var newSection, handlebarsTemplate;

        if (typeof section === undefined) {
            newSection = "htmlBody";
        } else if (section === "body") {
            newSection = "htmlHead";
        } else if (section === "head") {
            newSection = "htmlBody";
        }

        handlebarsTemplate = fs.readFileSync(viewsDir + '/' + file + '.html', 'utf8');
        Handlebars.registerPartial(newSection, handlebarsTemplate);
    };
};

Whenever I call "renderHtml()" it throws an error that the function is undefined. How do I proceed?

1 Answer 1

2

You never returned your renderHtml method. Try this:

module.exports = function(fs, viewsDir) {
    var renderHtml = function(file, section) {
        var newSection, handlebarsTemplate;
        if (typeof section === undefined) {
            newSection = "htmlBody";
        } else if (section === "body") {
            newSection = "htmlHead";
        } else if (section === "head") {
            newSection = "htmlBody";
        }
        handlebarsTemplate = fs.readFileSync(viewsDir + '/' + file + '.html', 'utf8');
        Handlebars.registerPartial(newSection, handlebarsTemplate);
    };
    return renderHtml;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.