EJS 并不专门支持块,但是可以通过包含页眉和页脚来实现布局,如下所示:
<%- include('header') -%> <h1> Title </h1> <p> My page </p> <%- include('footer') -%>
https://github.com/mde/ejs#layouts
您可以将 base.ejs 分成两个文件,页眉和页脚,如下所示:
header.ejs
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>My Diary</title>
<link rel="stylesheet" href="stylesheets/bootstrap.min.css">
<script src="javascripts/jquery.js" ></script>
<script src="javascripts/bootstrap.min.js"></script>
</head>
<body>
页脚.ejs
<script type="text/javascript">
$(document).ready(function(){
});
</script>
</body>
</html>
有人制作了具有块继承能力的EJS(https://github.com/mafintosh/pejs)
直接来自文档(2018 年 1 月 1 日检索):
使用块很容易实现模板继承。只需声明 带有一些锚定块的
:base.html
<body> Hello i am base <%{{ content }}%> </body>
然后是一个
渲染child.html
base.html
<%{ './base.html' }%> <%{ content %> i am inserted in base <%} %>
要渲染示例,只需渲染
child.html
pejs.render('./child.html', function(err, result) { console.log(result); });
看起来不错。我将在我自己的项目中尝试这个。
您可以使用
ejs-locals
或 ejs-mate
引擎进行 ejs
抱歉迟到了。我也有同样的情况。你能做的就是在对象的属性中传递你想要渲染的内容。像这样:
<%- include('/partials/',{
title: 'my title',
tags: [
'<h1>Hi, my name is this</h1>'
]
});
%>
EJS不支持块,但这是我实施的解决方案。希望有帮助。
我找到了另一个库:https://www.npmjs.com/package/express-ejs-layouts(本周下载量> 11k)
支持块继承,提取视图中的css + css并将其放置到特定位置。
您可以在上面的 NPMJS 链接中查看示例代码。
一个可能的解决方法是在你中间添加一个
div
和 include(aBlock)
base.ejs
:
<!-- your-header -->
...
<div class="main-container">
<%- include(aBlock) %>
</div>
...
<!-- your-footer -->
并从服务器传递变量。例如在 Express 中:
app.get('/',(req,res)=>{
res.render('base', {aBlock: './home'})
})
// or
app.get('/about',(req,res)=>{
res.render('base', {aBlock: './about'})
})
鉴于
home.ejs
和about.ejs
与base.ejs
位于同一文件夹中,否则相应地修复路径