Nodejs 求指导如何往ejs的include里面传参数

发布于 1周前 作者 songsunli 来自 nodejs/Nestjs

Nodejs 求指导如何往ejs的include里面传参数

rt

3 回复

当然可以。下面是一个详细的回答,旨在解释如何在 Node.js 中使用 EJS 模板引擎时向 include 块传递参数。

如何向 EJS 的 include 块传递参数

在使用 EJS 时,你可能会遇到需要在 include 块中传递变量的情况。EJS 提供了直接的方式来实现这一点。下面将通过一个简单的例子来展示如何操作。

示例代码

首先,假设我们有三个文件:index.ejs, header.ejs, 和 footer.ejs

1. index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!-- Include header and pass a variable -->
    <%- include('header', { title: 'Welcome to My Website' }) %>

    <!-- Your main content here -->

    <!-- Include footer and pass a variable -->
    <%- include('footer', { message: 'Thanks for visiting!' }) %>
</body>
</html>

2. header.ejs

<header>
    <h1><%= title %></h1>
</header>

3. footer.ejs

<footer>
    <p><%= message %></p>
</footer>

解释

  1. index.ejs: 在这里,我们使用 <%- include('filename', data) %> 语法来包含其他模板文件,并传递数据对象作为第二个参数。这个数据对象中的键值对会被包含的模板文件所访问。

  2. header.ejs: 在这个文件中,我们使用 <%= title %> 来显示从 index.ejs 传递过来的 title 变量。

  3. footer.ejs: 同样地,<%= message %> 显示从 index.ejs 传递的 message 变量。

运行代码

为了运行这些文件,你需要确保你的 Node.js 项目已经安装了 EJS 模块。你可以通过运行以下命令来安装:

npm install ejs

然后,在你的服务器端脚本(例如 server.js)中,设置 EJS 作为视图引擎并渲染 index.ejs

server.js

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

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

// 渲染 index.ejs
app.get('/', (req, res) => {
    res.render('index');
});

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

这样,当你访问应用的根路径(例如 http://localhost:3000/)时,你将看到带有传递参数的头部和尾部内容。

通过这种方式,你可以轻松地在 EJS 的 include 块中传递和使用变量。希望这对你有所帮助!


在express里面可以直接使用render过来的,不需要传参数

回答:

要在EJS的<%- include %>标签中传递参数,你可以使用局部变量(locals)。局部变量可以在整个EJS模板中访问,包括被包含的部分。

示例代码

假设你有一个主模板index.ejs和一个被包含的子模板header.ejs。你想在header.ejs中使用传递过来的参数。

1. 主模板 index.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <%- include('./header.ejs', { title: 'Hello World' }) %>
    <h1>Main Content</h1>
</body>
</html>

2. 被包含的子模板 header.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
</body>
</html>

在这个例子中,我们在index.ejs中使用<%- include('./header.ejs', { title: 'Hello World' }) %>title参数传递给header.ejs。然后在header.ejs中通过<%= title %>来使用这个参数。

注意事项

  • 如果你在服务器端渲染EJS模板,确保在调用res.render时传递正确的局部变量。
  • 如果你需要在多个地方传递相同的参数,可以考虑使用EJS的布局或部分布局功能。

这样你就可以在EJS的include中传递并使用参数了。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!