[英]NodeJS require a function inside module exports?
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 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 - The function to register a handlebars partial 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);
};
};
Whenever I call "renderHtml()" it throws an error that the function is undefined. 每当我调用“ renderHtml()”时,都会引发错误,指出该函数未定义。 How do I proceed?
我该如何进行?
You never returned your renderHtml
method. 您从未返回过
renderHtml
方法。 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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.