I'm trying to understand if I can render via the res.render() function or in some other way a multiple set of view(s).
In the home.handlebars I have the following code
<h1>Home</h1>
and I want to replicate it into the default layout a "N" number of times.
After looking around as far as I understand the .render() function commits the entire transmission so if i write multiple res.render(); res.render(); is not going to work.
Am I approaching this from a complete wrong side or I am missing something? Do I need to create a "dynamic" view and than pass it one single time to the res.render()?
Thanks.
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'));
});
Yes you can, here is some code I use do help do that. I have a partials directory inside of my views directory that I pull from.
Directory structure:
package.json
/lib/app.js
/templates/offering-links/handlebars
/partials/offering-links-script/handlebars
Helper code to use the partials:
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);
And then calling renderPage.
response.renderPage(
"offering-links",
{
title: "Offering Links",
offerings: offerings,
partials: {
script: path.join("partials", "offering-links-script")
},
baseURL: contextRoot
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.