Node.js + express + handlebars displays multiple views in a single request

I'm trying to figure out if I can render using the res.render () function or in some other way a multiple set of views.

In home.handlebars I have the following code

<h1>Home</h1>

and I want to replicate it to the default layout "N" a number of times.

Looking around, as I understand it, the .render () function captures the entire transfer, so if I write a few res.render (); res.render (); will not work.

Am I approaching this from the completely wrong side, or am I missing something? Do I need to create a “dynamic” view and pass it once to res.render ()?

Thank.

Attached code for test purposes:

var express=require('express');
var app=express();

// set up handlebars view engine
var handlebars = require('express-handlebars').create({ defaultLayout:'main' });

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');


app.set('port', process.env.PORT || 8888);

app.use(express.static(__dirname+'/public'));

app.get('/', function(req, res) {
    res.render('home');
    res.render('home');
    res.render('home');
});


// 404 catch-all handler (middleware)
app.use(function(req, res, next){
    res.status(404);
    res.render('404');
});

// 500 error handler (middleware)
app.use(function(err, req, res, next){
    console.error(err.stack);
    res.status(500);
    res.render('500');
});

app.disable('x-powered-by');

app.listen(app.get('port'),function(){
    console.log('express started on port:'+app.get('port'));
});
+4
1

, , , . partials , .

:

package.json
    /lib/app.js
        /templates/offering-links/handlebars
            /partials/offering-links-script/handlebars

:

function partialsHelper (request, response, next) {
        response.renderPage = function (template, options, callback) {
            var partials = (options && options.partials) || {};

            partials.footer = path.join("partials", "footer");
            partials.header = path.join("partials", "header");
            options.partials = partials;

            //disable cache for dynamic content
            if (request.method === "GET") {
                response.setHeader("Cache-Control", "no-cache");
            }
            // TODO: figure about max-age for cachable content

            return response.render(template, options, callback);
        };
        return next();
    }
    app.use(partialsHelper);

renderPage.

response.renderPage(
    "offering-links",
    {
        title: "Offering Links",
        offerings: offerings,
        partials: {
            script: path.join("partials", "offering-links-script")
        },
        baseURL: contextRoot
    }
);
0

Source: https://habr.com/ru/post/1584881/


All Articles