Layouts in Express 3 and EJS

こ雲淡風輕ζ 提交于 2019-12-03 06:46:15

问题


In version 3 of Express some features were removed:

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

The partial() can be changed for EJS own feature called include, but what is the alternative for layouts?


回答1:


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.

Install ejs-locals

npm install ejs-locals --save

Use ejs-locals as your app engine in app.js

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.




回答2:


I struggled with this as well. So I put up a github project with an example for ejs and dustjs.

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.




回答3:


You can mimic the EJS layouts in Express 2.x with the "include" option. See my answer here:

https://stackoverflow.com/a/12477536/446681



来源:https://stackoverflow.com/questions/12616694/layouts-in-express-3-and-ejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!