Express 3和EJS中的布局

art*_*olk 16 ejs node.js express

在Express的第3版中,删除了一些功能:

the concept of a "layout" (template engine specific now)
partial() (template engine specific)
Run Code Online (Sandbox Code Playgroud)

更改日志:https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x

partial()可以更改EJS叫自己的特点include,但什么是布局的选择吗?

cho*_*ovy 18

我也在努力解决这个问题.所以我提出了一个github项目,其中包含ejs和dustjs的示例.

https://github.com/chovy/express-template-demo

我不确定partial和include之间的区别,你不需要显式地将数据传递给include.不知道你为什么要偏爱.

但是对于布局,您只需指定一个这样的块:

//layout.ejs
<html>
<%- body %>
</html>

//page1.ejs
<% layout('layout') -%>
This is loaded from page 1 and overrides <%- body %> in the layout.ejs.
Run Code Online (Sandbox Code Playgroud)

如果有人想添加更多示例,只需提交拉取请求即可.

  • 似乎来自`layout()`的支持来自`ejs-locals`,你使用的不是EJS本身. (2认同)

And*_*ndy 13

似乎从Express 3,布局功能被委托给模板引擎的责任.您可以使用ejs-locals(https://github.com/RandomEtc/ejs-locals)进行布局.

安装ejs-locals

npm install ejs-locals --save
Run Code Online (Sandbox Code Playgroud)

在app.js中使用ejs-locals作为您的应用引擎

var express = require('express');
var engine = require('ejs-locals');
...

app.engine('ejs', engine);
app.set('view engine', 'ejs');
Run Code Online (Sandbox Code Playgroud)

现在您可以使用布局

layout.ejs
<body>
  <%- body %>
</body>

index.ejs
<% layout('layout') -%>

<div class="container">
<div class="jumbotron">
...
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用express-partials(https://github.com/publicclass/express-partials).两者做同样的事情,所以这只是你的选择.

  • 不幸的是,ejs-locals已经不再维护了. (5认同)