我创建了一个用把手注册新部分的功能。我不想把所有内容都塞进同一个文件中,所以我使用模块导出来导出函数。
home.js - 用于渲染视图
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 - 注册把手部分的功能
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);
};
};
每当我调用“renderHtml()”时,它都会抛出一个函数未定义的错误。我该怎么办?
答案 0 :(得分:2)
您从未返回renderHtml
方法。试试这个:
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;
};