如何使用 node.js 和 express 和 EJS 正确 "include" 一个 EJS 文件

How to properly "include" an EJS file using node.js with express and EJS

我开始学习 node.js,并且已经安装了 express 并且正在使用 EJS 和 express。

我有以下代码(主要由 express-generator 生成):

app.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

index.ejs

<!DOCTYPE html>
<html>

  <head><% include partials/head.ejs %></head>

  <body>
  <% include partials/header.ejs %>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>

    <% include partials/footer.ejs %>
    <% inlcude partials/javascripts.ejs %>

  </body>
</html>

javascripts.ejs

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>

我的问题是出现此错误:

Unexpected identifier in /var/www/HomeWatch.com/views/index.ejs while compiling ejs

SyntaxError: Unexpected identifier in /var/www/HomeWatch.com/views/index.ejs while compiling ejs
    at Object.Function (<anonymous>)
    at Object.Template.compile (/var/www/HomeWatch.com/node_modules/ejs/lib/ejs.js:464:12)
    at Object.compile (/var/www/HomeWatch.com/node_modules/ejs/lib/ejs.js:288:16)
    at handleCache (/var/www/HomeWatch.com/node_modules/ejs/lib/ejs.js:147:16)
    at View.exports.renderFile [as engine] (/var/www/HomeWatch.com/node_modules/ejs/lib/ejs.js:350:14)
    at View.render (/var/www/HomeWatch.com/node_modules/express/lib/view.js:126:8)
    at tryRender (/var/www/HomeWatch.com/node_modules/express/lib/application.js:639:10)
    at EventEmitter.render (/var/www/HomeWatch.com/node_modules/express/lib/application.js:591:3)
    at ServerResponse.render (/var/www/HomeWatch.com/node_modules/express/lib/response.js:961:7)
    at module.exports (/var/www/HomeWatch.com/routes/index.js:6:7)

它仅在包含 javascripts.ejs 时发生,如果我删除它,页面加载正常。

这是我的文件夹结构(我省略了我认为您不需要的内容,但整个 express 结构都在那里)

-bin
--www
routes
-index.js
views
-partials
--footer.ejs
--head.ejs
--header.ejs
--javascripts.ejs
-error.ejs
-index.ejs
app.js
package.json

看来把javascripts.ejs改名为javascript.ejs就可以解决问题了。。。我都不敢问为什么了。。。