[英]Dynamic partial in handlebars
下面的代碼工作正常但是routes /
和/signup
會顯示相同的東西(標題除外),因為res.render中的第一個參數沒有做任何事情,因為在布局中我有{{< index}}
來渲染視圖用名稱索引。 我想要的是動態傳遞我想渲染的部分(基本上我希望res.render的第一個參數生效)。
app.js
/* Variable declarations */
var express = require('express'),
hbs = require('hbs'),
app = express();
/* Setttings */
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
app.set('view options', { layout: 'layout' });
/* Register Partials */
hbs.registerPartials(__dirname + '/views');
/* Routes */
app.get('/signup', function (req, res) {
res.render('index', {title: 'Welcome'});
});
app.get('/signup', function (req, res) {
res.render('signup', {title: 'Sign Up'});
});
/* Listeners */
app.listen(80, function () {
console.log('App started...');
});
Layout.hbs
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{> index}}
</body>
</html>
作為Handlerbars 3.0的一部分,包括動態部分。 你可以在這里找到參考。 使用這種新語法,可以評估並動態替換partial的名稱。 我正在使用"express-handlebars": "2.0.1",
Layout.hbs
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{> (whichPartial) }}
</body>
</html>
App.js
/* Routes */
app.get('/', function (req, res) {
res.render('index', {title: 'Welcome'
whichPartial: function() {
return "thePartialNameForIndex";
}
});
});
app.get('/signup', function (req, res) {
res.render('signup', {title: 'Sign Up'
whichPartial: function() {
return "thePartialNameForSignup";
}
});
});
其中, thePartialNameForIndex
和thePartialNameForSignup
是/views
分配的部分的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.