把手中的动态局部

Alm*_*mis 3 node.js express handlebars.js

下面的代码可以正常工作,但可以路由,/并且/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...');
});
Run Code Online (Sandbox Code Playgroud)

Layout.hbs

<!DOCTYPE html>
<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        {{> index}}
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 5

作为Handlerbars 3.0的一部分,包含了动态部分。您可以在此处找到参考。使用这种新语法,将评估部分名称并进行动态替换。我正在使用"express-handlebars": "2.0.1",

Layout.hbs

<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
  </head>
  <body>
    {{> (whichPartial) }}
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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";
       }
   });
});
Run Code Online (Sandbox Code Playgroud)

其中thePartialNameForIndexthePartialNameForSignup是在中分配的局部变量的名称/views