Express和Handlebars:实现多个Defaultlayouts

时间:2019-12-09 09:52:12

标签: node.js express express-handlebars

我需要为我的项目nodejs(销售点)提供两个defaultlayout,第一个:用于身份验证页面和新用户(出纳)的注册(带有自己的CSS代码),第二个用于仪表板(pos接口)以及产品添加页面...)(也有其自己的CSS代码)。

我的代码的结构应为:

views/
   layouts/
    mainDashboard.hbs
    mainLogin.hbs
   dashboard.hbs
   addProduct.hbs
   login.hbs
   register.hbs

我在server.js中的代码(只需设置一个DefaultLayout):

const express = require("express");
const exphbs = require("express-handlebars");
const app = new express();

// view enginge
app.engine(
  "handlebars",
  exphbs({
    defaultLayout: "mainlogin" ,
  })
);
app.set("view engine", "handlebars");

现在我想用不同的CSS代码制作两个不同的布局, 我找到了this post,但我不了解解决方案(我指定我是node.js的初学者,并且该站点是我的第一个项目,所以我需要更多详细信息)

1 个答案:

答案 0 :(得分:1)

要说明帖子中发生的情况,您需要了解一些基本知识:

1)res.render是一个表达函数,用于呈现视图(如.hbs,.ejs等)。通常,您如何使用渲染功能是这样的:

res.render('index.hbs')

哪个返回一些html并将其写入浏览器。

2)app.use用于将中间件(除了具有3个参数的函数以外)添加到中间件链。

app.use(middleware1);
app.use(middleware2);

对于上述示例,每个http请求都将通过app.getapp.post之类的处理程序通过Middleware1 THEN middleware2 THEN。

因此基本上可以创建一个中间件来覆盖res.render函数


现在,要使用此处显示的代码,

在视图内为两个主题制作两个文件夹。例如,

views/
   theme1/
       index.hbs
   theme2/
       index.hbs

index.js文件中,它应该是普通的快速代码,然后添加中间件:

const express = require("express");
const app = express();

...
...
...

app.use(function(req, res, next) {
  // cache original render
  var _render = res.render;

  res.render = function(view, options, done) {
    // custom logic to determine which theme to render
    var theme = getThemeFromRequest(req);
    // ends up rendering /themes/theme1/index.hbs
    _render.call(this, 'themes/' + theme + '/' + view, options, done);
  };
  next();
});

function getThemeFromRequest(req) {
  // in your case you probably would get this from req.hostname or something
  // but this example will render the file from theme2 if you add ?theme=2 to the url
  if(req.query && req.query.theme) {
    return 'theme' + req.query.theme;
  }
  // default to theme1
  return 'theme1';
}
app.listen(8080, ()=>console.log("Started"));

现在让我们说一条路线:

app.get('/', (req, res) =>{
    res.render('index.hbs');
});

现在转到http://localhost:8080/,它将渲染theme1/index.hbs,如果您执行http://localhost:8080/?theme=theme2,它将渲染theme2/index.hbs

希望您能理解其中的解释。