Node.js - EJS - 包括部分

jef*_*eon 57 ejs node.js

我正在尝试将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").

EJS包括

  • 这应该是正确的答案,因为 ejs / express 的开发人员更新了代码。 (2认同)
  • 在 ejs2 中,我有这样的代码,看起来像这样并且可以工作。&lt;% include myview.ejs %&gt; 在 ejs3 中,它需要看起来像这样 &lt;%- include('myview.ejs') %&gt; 猜猜我花了多少小时才意识到我必须在开头添加破折号?(只需添加此评论,以防其他处于相同情况的人阅读它。) (2认同)

asa*_*j07 22

适用于 Express 4.x :

按照正确的方式在模板中包括谐音这个你应该使用:

<%- include('partials/youFileName.ejs') %>.

您正在使用:

<% include partials/yourFileName.ejs %>

已弃用。


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作为您的布局.

  • 我丢失了 ) 错误,我必须把它写成 &lt;%- include ('partials/navbar.ejs') %&gt; (2认同)

Dan*_*Ram 9

从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)