Nodejs 在片段视图partial中无法调用render过来的参数

Nodejs 在片段视图partial中无法调用render过来的参数

路由里面:res.render(‘user’, { title: user.name, posts: posts, }); user.ejs里面:<% if (user) { %> <%- partial(‘say’) %> <% } %> <%- partial(‘posts’) %> posts里面:<% posts.forEach(function(post, index) { if (index % 3 == 0) { %> … 程序大概是这样的,但是报错说,posts is not defined ,传过来的posts对象在片段试图中无法获取到


2 回复

Node.js 在片段视图(partial)中无法调用 render 过来的参数

在使用 EJS 模板引擎时,有时会遇到在片段视图(partial)中无法访问通过 res.render 传递的参数的问题。这个问题通常是由于片段视图中作用域问题导致的。

示例代码

路由文件(例如 app.jsroutes.js

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

// 设置模板引擎
app.set('view engine', 'ejs');

app.get('/user', function(req, res) {
    const user = { name: 'John Doe' };
    const posts = [
        { title: 'Post 1' },
        { title: 'Post 2' },
        { title: 'Post 3' }
    ];
    
    // 渲染用户页面,并传递参数
    res.render('user', {
        title: user.name,
        posts: posts
    });
});

module.exports = app;

主模板文件(user.ejs

<!DOCTYPE html>
<html>
<head>
    <title><%- title %></title>
</head>
<body>
    <% if (user) { %>
        <%= partial('say') %>
    <% } %>

    <%= partial('posts', { locals: { posts: posts } }) %>
</body>
</html>

片段视图 say.ejs

<h1>Welcome, <%= user.name %>!</h1>

片段视图 posts.ejs

<ul>
<% posts.forEach(function(post, index) { %>
    <li><%= post.title %></li>
<% }); %>
</ul>

解释

  1. 传递参数给片段视图

    • user.ejs 中,当调用 partial('posts') 时,需要将 posts 对象作为局部变量传递给片段视图。这可以通过在 partial 函数中传递一个对象 { locals: { posts: posts } } 来实现。
  2. 确保作用域正确

    • 在片段视图中,如果需要访问父级模板传递的变量,必须确保这些变量在片段视图中也存在。通过传递局部变量,可以确保片段视图能够访问到所需的变量。

通过上述方法,可以在片段视图中正确地访问通过 res.render 传递的参数,从而避免出现 posts is not defined 的错误。


在你的例子中,posts 对象没有正确传递给 posts.ejs 部件视图。你需要确保在调用 partial 时正确传递数据。

示例代码

路由部分

app.get('/user', (req, res) => {
    const user = {
        name: 'John Doe'
    };
    const posts = [
        { title: 'Post 1' },
        { title: 'Post 2' },
        { title: 'Post 3' }
    ];
    res.render('user', {
        title: user.name,
        user: user,
        posts: posts
    });
});

user.ejs

<% if (user) { %>
    <%= partial('say', { user: user }) %>
<% } %>

<%= partial('posts', { posts: posts }) %>

say.ejs

<div>
    Hello, <%= user.name %>!
</div>

posts.ejs

<ul>
<% posts.forEach(function(post, index) { %>
    <li><%= post.title %></li>
<% }); %>
</ul>

解释

  1. 路由部分:将 userposts 对象一起传递给 res.render 方法。
  2. user.ejs:使用 partial 函数传递 userposts 参数。
  3. say.ejsposts.ejs:通过 partial 函数接收传递的参数,并正确使用它们。

通过这种方式,你可以确保 posts 对象可以在 posts.ejs 中被正确访问和使用。

回到顶部