我在使用handlebars.js hbs包装 in express.js。我有很好的模板,但是我需要添加要用我的视图呈现的部分。
我想做这样的事情:
hbs.registerPartial('headPartial', 'header');
// where "header" is an .hbs file in my views folder然而,它抛出了一个“标头部分找不到”。
如果我将一个html字符串传递给第二个param,我可以使registerPartial工作,但是我想为我的部分使用单独的视图文件。
我还没有找到任何关于这方面的文档,但希望我可能只是错过了一些简单的东西。
有人知道如何在registerPartial方法中使用视图文件吗?如果是,我如何实现这一点?
更新
为了提供更多的上下文,让我添加更多的代码。这是我的“服务器”文件- app.js
var express = require('express')
, routes = require('./routes')
, hbs = require('hbs');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// this is the line that generates the error
hbs.registerPartial('headPartial', 'header');
// What I'm expecting is for "headPartial" to be a compiled template partial
// of the template within views/header.hbs, but it is not loading this way.
// If I do something like hbs.registerPartial('headPartial', '<p>test</p>');
// then it does work. I need to know how to pass an .hbs file to the
// registerPartial method.
// Routes
app.get('/', routes.index);
app.listen(3000);这是我的routes.index文件:
exports.index = function(req, res){
res.render('index', { title: 'Express' })
};在“视图”文件夹中,有三个模板:
views/
header.hbs (this is my partial)
index.hbs
layout.hbs在我的index.hbs文件中,我将“headPartial”部分调用为:
{{> headPartial}}任何帮助都是非常感谢的。
发布于 2012-10-03 00:36:59
此代码加载目录中的所有部分模板,并通过文件名使其可用:
var hbs = require('hbs');
var fs = require('fs');
var partialsDir = __dirname + '/../views/partials';
var filenames = fs.readdirSync(partialsDir);
filenames.forEach(function (filename) {
var matches = /^([^.]+).hbs$/.exec(filename);
if (!matches) {
return;
}
var name = matches[1];
var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
hbs.registerPartial(name, template);
});发布于 2013-06-15 18:42:10
为了方便起见,registerPartials提供了一种从特定目录加载所有部分的快速方法:
var hbs = require('hbs');
hbs.registerPartials(__dirname + '/views/partials');从目录加载的部分将根据其文件名命名,其中空格和连字符被替换为下划线字符:
template.html -> {{> template}}
template 2.html -> {{> template_2}}
login view.hbs -> {{> login_view}}
template-file.html -> {{> template_file}}干杯!
发布于 2011-11-14 22:33:40
看起来,创建一个变量并手动提取模板代码是可行的:
var hbs = require('hbs')
, fs = require('fs')
, headerTemplate = fs.readFileSync(__dirname + '/views/_header.hbs', 'utf8');后来:
hbs.registerPartial('headPartial', headerTemplate); https://stackoverflow.com/questions/8059914
复制相似问题