Nodejs ejs include问题

Nodejs ejs include问题

//index.js
res.render(‘index’, { title:chunk});
//index.ejs
<% include header.ejs%>

怎么引用不进去!! 还报Error:filename option is required for includes 这是什么原因的??求助。。。。

5 回复

当然可以。你遇到的问题是因为 EJS 模板引擎在处理 include 指令时需要明确指定文件路径。错误信息 Error: filename option is required for includes 提示你需要提供文件名选项。

解释

EJS 模板引擎使用 <%- include('path/to/file') %> 来包含其他模板文件。默认情况下,EJS 需要知道这些文件的位置,以便正确解析和渲染它们。这就是为什么你需要提供一个明确的文件路径。

示例代码

假设你的目录结构如下:

project/
├── views/
│   ├── index.ejs
│   ├── header.ejs
├── routes/
│   └── index.js
└── app.js

app.js

首先确保你的 Express 应用配置了正确的视图引擎和视图目录:

const express = require('express');
const path = require('path');
const app = express();

// 设置视图引擎为 EJS
app.set('view engine', 'ejs');

// 设置视图文件目录
app.set('views', path.join(__dirname, 'views'));

app.get('/', (req, res) => {
    res.render('index', { title: 'Hello World' });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

routes/index.js

在这个文件中,你可以定义路由逻辑。假设我们已经将路由逻辑移到了单独的文件中,例如 routes/index.js

module.exports = (app) => {
    app.get('/', (req, res) => {
        res.render('index', { title: 'Hello World' });
    });
};

然后在 app.js 中引入它:

const indexRouter = require('./routes/index')(app);

views/index.ejs

index.ejs 文件中,你可以使用 include 指令来包含其他模板文件。确保提供正确的路径:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <!-- 包含 header.ejs -->
    <%- include('../components/header.ejs') %>

    <h1>Welcome to <%= title %></h1>
</body>
</html>

注意事项

  1. 路径:确保路径正确。相对路径应从当前模板文件开始计算。
  2. 文件名:确保 header.ejs 文件存在于指定的路径中。
  3. 语法:注意使用 <%- 而不是 <%,因为后者不会输出内容。

通过上述步骤,你应该能够成功地使用 EJS 的 include 指令来包含其他模板文件,并避免错误。


<%-include header.ejs%>

可以了。。谢谢!!

我这边怎么不可以呀,使用这个需要注意什么吗?求解答

你在使用 EJS 的 include 功能时遇到了一个错误,提示 Error: filename option is required for includes。这是因为 EJS 在处理 include 语句时需要知道文件的路径。你可以通过设置 viewspartial 文件夹来解决这个问题。

首先,确保你的项目结构是这样的:

project-root/
│
├── views/
│   ├── index.ejs
│   ├── header.ejs
│   └── partials/
│       └── common-header.ejs
│
├── routes/
│   └── index.js
└── app.js

接下来,在 app.js 中设置 EJS 的视图引擎,并指定 partials 文件夹的位置:

const express = require('express');
const app = express();

// 设置视图引擎为 EJS
app.set('view engine', 'ejs');

// 指定视图文件夹
app.set('views', './views');

// 指定部分视图文件夹
app.locals.partials = {
    header: 'partials/common-header'
};

// 静态文件服务
app.use(express.static('public'));

// 路由
require('./routes/index')(app);

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

然后,在 index.ejs 中使用 include 语句引用部分视图:

<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <!-- 引用部分视图 -->
    <%- include(partials.header) %>

    <h1>Welcome to <%= title %></h1>
</body>
</html>

最后,确保 header.ejs 文件存在于 partials 文件夹中,或者直接将 header.ejs 文件移动到 partials 文件夹中并修改 index.ejs 中的 include 语句。

通过以上步骤,你应该可以正确地引用部分视图而不会遇到错误。

回到顶部