我正在尝试将Embedded Javascript渲染器用于节点:https: //github.com/visionmedia/ejs
我想知道如何在.ejs视图文件中包含另一个视图文件(部分).
pky*_*eck 114
使用Express 3.0:
<%- include myview.ejs %>
Run Code Online (Sandbox Code Playgroud)
路径是相对于包含文件的调用者,而不是来自设置的views目录app.set("views", "path/to/views").
cze*_*asz 17
在Express中4.x我使用以下内容加载ejs:
var path = require('path');
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.ejs exists in the app directory
app.get('/hello', function (req, res) {
res.render('index', {title: 'title'});
});
Run Code Online (Sandbox Code Playgroud)
然后你只需要两个文件就可以了 - views/index.ejs:
<%- include partials/navigation.ejs %>
Run Code Online (Sandbox Code Playgroud)
而且views/partials/navigation.ejs:
<ul><li class="active">...</li>...</ul>
Run Code Online (Sandbox Code Playgroud)
您还可以告诉Express使用ejshtml模板:
var path = require('path');
var EJS = require('ejs');
app.engine('html', EJS.renderFile);
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
res.render('index.html', {title: 'title'});
});
Run Code Online (Sandbox Code Playgroud)
最后你还可以使用ejs布局模块:
var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);
Run Code Online (Sandbox Code Playgroud)
这将使用views/layout.ejs作为您的布局.
从Express 4.x开始
app.js
// above is all your node requires
// view engine setup
app.set('views', path.join(__dirname, 'views')); <-- ./views has all your .ejs files
app.set('view engine', 'ejs');
Run Code Online (Sandbox Code Playgroud)
error.ejs
<!-- because ejs knows your root directory for views, you can navigate to the ./base directory and select the header.ejs file and include it -->
<% include ./base/header %>
<h1> Other mark up here </h1>
<% include ./base/footer %>
Run Code Online (Sandbox Code Playgroud)