找不到包含包含文件

Could not find include include file

我正在 运行搭建一个简单的服务器

var express = require('express')
var app = express()

app.set('view engine', 'ejs'); 
app.use(express.static('public')) 

// home page request handler
app.get('/', function (req, res) {

    res.render('home')
})

// initializes request listener
app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Server is listening");
})

当我对主页进行GET请求时,运行-time抛出如下错误

Error: Could not find include include file.
    at getIncludePath (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:152:13)
    at includeSource (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:276:17)
    at /home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:629:26
    at Array.forEach (native)
    at Object.generateSource (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:605:15)
    at Object.compile (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:509:12)
    at Object.compile (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:358:16)
    at handleCache (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:201:18)
    at tryHandleCache (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:223:14)
    at View.exports.renderFile [as engine] (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:437:10)

我不明白这个错误。有任何想法吗?我在 Cloud9 工作。

我的目录结构是

v1.1
  +---views
  |     +---- home.ejs
  |     +---- partials
  |               +------ header.ejs
  |               +------ footer.ejs
  |
  +----app.js

home.ejs

<% include header %>
<h1>welcome</h1>
<% include footer %>

header.ejs

<DOCTYPE! html>
    <html>
        <head>
            <title>
                <link rel="stylesheet" hreff="app.css">
            </title>
        </head>
    <body>

footer.ejs

    </body
</html>

包含路径是相对的,您需要更新路径以包含 "partials" 子文件夹,例如

<% include partials/header %>
<h1>welcome</h1>
<% include partials/footer %>

docs

试试这个:

<% include header %>

    <h1>welcome</h1>

<% include footer%>

试试这些:

<% include header.ejs %>
<% include header %>
<%- include('header.ejs'); -%>
<%- include('./header.ejs'); -%>
  1. VS Code
  2. Left Side File Explorer
  3. Right Click on the '.ejs' file
  4. Click on 'Copy Path'
  5. Then paste that path
<%- include('YOUR_PATH/GOES_HERE') %>

就我而言, OS Ubuntu,路径是这样的

<%- include('/media/username/diskname/foldername/nodejsApp/views/body/header.ejs') %>

编辑

我在写答案时忘记了'%'。

<%- 包括 ('Filename without adding .ejs') %>

先决条件:确保文件名与上面声明的名称相关联。即(Header 不等于 header。)

对我来说,我必须设置根参数,

ejs.render(
  html,
  {},
  {
    root: process.cwd(),
  }
)

然后像这样使用它,

<%- include('/footer/index.ejs'); %>

不要将扩展名放在文件名之后。例如,这样做:

include("file", { item: 123})

...不是这个:

include("file.ejs", { item: 123})

如果循环中有多个包含,请不要将整个循环放在一个 <% %> 块中。将开始和结束放在它们自己的 <% %> 中,并将包含在 <%- %> 标记中。它不适用于 <% %> 标签,您需要使用 <%- %>:

<% for(const item of items) { %>
    <%- include("file", { item: 123}) %>
<% } %>