node.js ejs '部分未定义'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11351691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ejs 'partial is not defined'
提问by lostAstronaut
Okay I have a mostly static homepage but I wanted to have partial views that for navigation, footer ect. I'm using ejs and it looks like this:
好的,我有一个主要是静态的主页,但我想拥有用于导航、页脚等的部分视图。我正在使用 ejs,它看起来像这样:
my controller: home.js
我的控制器:home.js
// Dependencies
var express = require('express');
module.exports = {
get: function(req, res) {
app.set('view engine', 'ejs');
var model = {
layout:'home',
};
res.render('home');
}
};
My views directory has nav, home and footer all .ejs
我的视图目录包含导航、主页和页脚所有 .ejs
Then the actual html file stripped of text would look as following.
然后去除文本的实际 html 文件将如下所示。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<title>Tom Jones</title>
<!-- CSS -->
<link rel="stylesheet" href="/css/home.css" type="text/css" media="screen" >
</head>
<body>
<%- partial('nav') %>
<!--content part -->
<div id="showcontainer">
<section>
</section>
</div>
<div id="maincontainer">
<section>
</section>
</div>
</body>
</html>
The Problem When ever I test it out I run into the error partial is not defined. I tried requiring ejs but no success.
问题当我测试它时,我遇到了错误部分未定义。我尝试要求 ejs 但没有成功。
回答by Joshua
As @Pickels said, Partial was removed in 3.x. However, the most recent version of EJS provides a mechanism for including "partials", called "include":
正如@Pickels 所说,Partial 在 3.x 中被删除了。但是,最新版本的 EJS 提供了一种包含“部分”的机制,称为“包含”:
https://github.com/visionmedia/ejs#includes
https://github.com/visionmedia/ejs#includes
Includes are relative to the template with the include statement, for example if you have "./views/users.ejs" and "./views/user/show.ejs" you would use <% include user/show %>. The included file(s) are literally included into the template, no IO is performed after compilation, thus local variables are available to these included templates.
包含与包含语句的模板相关,例如,如果您有“./views/users.ejs”和“./views/user/show.ejs”,您将使用 <% include user/show %>。被包含的文件直接包含在模板中,编译后不执行 IO,因此这些包含的模板可以使用局部变量。
The following will work as a replacement for your old partial() function. You'll need to make tweaks elsewhere to support Express 3.x completely, but for the most part this seems to work well (better actually - less code and more performant).
以下将替代旧的 partial() 函数。您需要在其他地方进行调整以完全支持 Express 3.x,但在大多数情况下,这似乎运行良好(实际上更好 - 更少的代码和更高的性能)。
<% include nav.ejs %> <!-- replaces your old <%- partial('nav') %> -->
回答by Pickels
Partial was removed in 3.x. It's now up to the templating engine to provide partials.
部分在 3.x 中被移除。现在由模板引擎来提供部分。

