Dynamic partial in the steering wheel

The code below works fine, but the routes /

and /signup

will show the same thing (except for the title), because the first argument to res.render does nothing, and because there is a layout in the layout {{< index}}

that renders the view using the index name. I want to dynamically pass the part that I want to render (basically I want the first argument to res.render to have an effect).

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>

      

+3


source to share


1 answer


Handlerbars 3.0 includes dynamic subparts. You can find the link here . With this new syntax, the name of the partial is evaluated and dynamically replaced. I am using "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";
       }
   });
});

      

Where thePartialNameForIndex

and thePartialNameForSignup

is the name of the partial items highlighted in /views

.

+4


source







All Articles