Tôi đang sử dụng handlebars.js hbs wrapper trong express.js. Tôi có mẫu làm việc tốt, nhưng tôi cần phải thêm vào partials để được kết xuất với quan điểm của tôi.mô-đun Express.js hbs - đăng ký partials từ tệp .hbs
Tôi muốn làm điều gì đó như thế này:
hbs.registerPartial('headPartial', 'header');
// where "header" is an .hbs file in my views folder
Tuy nhiên, nó ném một "tiêu đề một phần không thể tìm thấy".
Tôi có thể thực hiện công việc registerPartial nếu tôi chuyển một chuỗi html tới tham số thứ hai, nhưng tôi muốn sử dụng các tệp xem riêng cho partials của tôi.
Tôi chưa tìm thấy bất kỳ tài liệu nào về vấn đề này, nhưng hy vọng tôi có thể thiếu điều gì đó dễ dàng.
Có ai biết cách sử dụng tệp xem trong phương pháp registerPartial không? Nếu vậy, làm thế nào để tôi thực hiện điều này?
CẬP NHẬT
Để cung cấp cho bối cảnh nhiều hơn, hãy để tôi thêm mã hơn. Dưới đây là "máy chủ" của tôi tập - 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);
Và đây là tập tin routes.index tôi:
exports.index = function(req, res){
res.render('index', { title: 'Express' })
};
Trong thư mục quan điểm của tôi, tôi có ba mẫu:
views/
header.hbs (this is my partial)
index.hbs
layout.hbs
Trong tệp index.hbs của tôi, tôi đang gọi phần 'headPartial' với:
{{> headPartial}}
Bất kỳ trợ giúp nào được đánh giá cao.
Nice. Một cách nhanh chóng để có tất cả partials có sẵn khi cần thiết! – swatkins
Cảm ơn Ben, điều này thực sự đã giúp rất nhiều. – Dave