node.js Express 3 和 EJS 中的布局
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12616694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Layouts in Express 3 and EJS
提问by artvolk
In version 3 of Express some features were removed:
在 Express 版本 3 中,删除了一些功能:
the concept of a "layout" (template engine specific now)
partial() (template engine specific)
Changelog: https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
更新日志:https: //github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
The partial()can be changed for EJS own feature called include, but what is the alternative for layouts?
该partial()可以更改EJS叫自己的特点include,但什么是布局的选择吗?
采纳答案by Andy
It seems that from Express 3, layout feature is delegated to the responsibility of template engines. You can use ejs-locals (https://github.com/RandomEtc/ejs-locals) for layout.
似乎从 Express 3 开始,布局功能被委托给模板引擎的责任。您可以使用 ejs-locals ( https://github.com/RandomEtc/ejs-locals) 进行布局。
Install ejs-locals
安装 ejs-locals
npm install ejs-locals --save
Use ejs-locals as your app engine in app.js
在 app.js 中使用 ejs-locals 作为您的应用引擎
var express = require('express');
var engine = require('ejs-locals');
...
app.engine('ejs', engine);
app.set('view engine', 'ejs');
Now you can use layout
现在您可以使用布局
layout.ejs
<body>
<%- body %>
</body>
index.ejs
<% layout('layout') -%>
<div class="container">
<div class="jumbotron">
...
Another option is to use express-partials (https://github.com/publicclass/express-partials). The two do the same thing, so it's just your choice.
另一种选择是使用 express-partials ( https://github.com/publicclass/express-partials)。两者做同样的事情,所以这只是你的选择。
回答by chovy
I struggled with this as well. So I put up a github project with an example for ejs and dustjs.
我也为此苦苦挣扎。所以我建立了一个 github 项目,其中包含 ejs 和dustjs 的示例。
https://github.com/chovy/express-template-demo
https://github.com/chovy/express-template-demo
I'm not sure the difference between a partial and an include, you don't need to explicitly pass data to an include. Not sure why you would want a partial.
我不确定部分和包含之间的区别,您不需要明确地将数据传递给包含。不知道为什么你想要部分。
But for a layout, you just specify a block like this:
但是对于布局,您只需指定一个像这样的块:
//layout.ejs
<html>
<%- body %>
</html>
//page1.ejs
<% layout('layout') -%>
This is loaded from page 1 and overrides <%- body %> in the layout.ejs.
If anyone wants to add more examples, just submit a pull request.
如果有人想添加更多示例,只需提交拉取请求。
回答by Hector Correa
You can mimic the EJS layouts in Express 2.x with the "include" option. See my answer here:
您可以使用“包含”选项模仿 Express 2.x 中的 EJS 布局。在这里看到我的回答:

