简体   繁体   English

Express 4 车把渲染无布局

[英]Express 4 handlebars render without layout

Is there a way in an express 4 app to render a view without using a layout?有没有办法在不使用布局的情况下在 express 4 应用程序中呈现视图?

I have a layout.hbs inside the project.我在项目中有一个 layout.hbs。 The file seems to be used without needing to register it anywhere and for most views that is ok, but what if just a single view needs to be rendered without?该文件似乎无需在任何地方注册即可使用,并且对于大多数视图都可以,但是如果只需要渲染单个视图怎么办?

Assuming you are using express-handlebars you can specify a different layout from your route/controller when you call the render method.假设您使用 express-handlebars,您可以在调用 render 方法时指定与路由/控制器不同的布局。 To get rid of the layout altogether you can set the layout to false .要完全摆脱布局,您可以将布局设置为false

router.get('/', function(req, res) {
    res.render('home', {layout: false});
});

https://github.com/ericf/express-handlebars#layouts https://github.com/ericf/express-handlebars#layouts

It should be clear, when you have data to render, that the layout should be merely an extra property of such data应该很清楚,当你有数据要渲染时, layout应该只是这些数据的一个额外属性

var data = {
    layout: false, 
    var1: var1,
    var2: var2
};

res.render('home', data); 

If you don't wish to give layout, you have to specify as layout: false .如果您不想给出布局,则必须指定为layout: false Otherwise app will crash.否则应用程序会崩溃。 You can configure as follow, if you need.如果需要,您可以进行如下配置。

app.get('/', (req, res, next) => {
    res.render('shop', { title: 'My Shop', layout: false })
});

For more congiguration of express-handlebars快速车把的更多配置

If you are using app.render() function to render html.如果您使用app.render()函数来渲染 html。 You are good to go with Rayan's answer .你很高兴接受Rayan 的回答 As on the express documentation itself mentions that, res.render() method also uses app.render() method under the hood.正如express 文档本身提到的那样, res.render()方法也在app.render()使用app.render()方法。

const app = require('express')();
app.set('view engine', 'hbs');
/**
 * Render email template with data
 * 
 * @param {String} emailTemplate email template path
 * @param {Object} renderParams Render parameters
 * @return {Promise} rendered template
 */
async function renderEmail(emailTemplate, renderParams) {
 const renderParams = { layout: false, ...otherRenderParams };

 return await new Promise((resolve, reject) => {
   app.render(emailTemplate, renderParams, function (err, html) {
       if (err) return reject(err);
       return resolve(html);
   });
 });
}

this worked for me to have 1 page without the main.handlebars layout:这对我来说有 1 个没有main.handlebars布局的页面:

  1. add layout false to the data object:将布局 false 添加到数据对象:
object.layout=false;
  1. render使成为
res.render('page', object);

adding .layout to the existing object allows you to easily still pass the object data..layout添加到现有对象允许您轻松地仍然传递对象数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM