[英]NodeJS require a function inside module exports?
我創建了一個函數來注冊帶有把手的新部分。 我不想將所有內容都塞在同一個文件中,所以我正在使用模塊導出來導出函數。
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()”時,都會引發錯誤,指出該函數未定義。 我該如何進行?
您從未返回過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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.