express 3.0.x 中默认不支持layout.ejs的解决方法

时间:2025-05-12 20:04:50

1.第一种方法用include

用<% include 模板名(可不加.ejs) %>的写法,具体如下

<% include header %>  //套用布局拆成两部分 header.ejs + footer.ejs

<form class="form-horizontal" method="post" >
//新的表单
</form> <% include footer %>

原来的express 2.0.x 中moren layout.ejs模板写法为,上边的header和footer相当于把layout以<%- body %>为界,拆成两部分

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<%- body %>
</body>
</html>

2.第二种方法 安装express-partial 模块(我自己还没试成功,先备份着????????)

①安装 express-partial

npm install express-partials

或者修改package.json里面的dependencies,添加"express-partials": "*",并执行npm install获得最新版

 ②在 app.js 中使用 express-partial
var partials = require('express-partials');
app.use(partials());

③在需要引用模板的地方调用layout:'模版名称'

 app.get('/reg', function (req, res) {
res.render('reg', {
title: '用户注册',
layout: 'layout.ejs'
});
});

注意:app.use(partials()); 一定要在 app.use(app.router); 前面