You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用EJS遍历嵌套评论对象数组生成层级嵌套HTML Div

搞定这个嵌套评论的Div生成很简单,用EJS的递归特性就能完美解决。我给你具体的实现方案,分步骤来:

1. 先明确你的评论数据结构

首先假设你的评论数组是这种嵌套格式(每个评论包含id、content和子评论数组children):

const comments = [
  {
    id: 1,
    content: "第一条更新后的评论",
    children: [
      {
        id: 2,
        content: "这是对评论ID 1(上方评论)的回复",
        children: [
          {
            id: 3,
            content: "这是对评论ID 2的回复",
            children: []
          }
        ]
      },
      {
        id: 4,
        content: "另一条对评论ID 1的回复",
        children: []
      }
    ]
  },
  {
    id: 5,
    content: "第二条顶级评论",
    children: []
  }
];

2. 用递归EJS模板渲染层级结构

最清晰的做法是创建一个递归的部分模板来处理单个评论及其子评论:

步骤2.1 创建comment.ejs部分模板

这个模板负责渲染单条评论,并且递归渲染它的所有子评论:

<div class="comment">
  <!-- 渲染当前评论内容 -->
  <div class="comment-text"><%= comment.content %></div>
  
  <!-- 如果有子评论,递归渲染 -->
  <% if (comment.children && comment.children.length > 0) { %>
    <div class="comment-replies">
      <% comment.children.forEach(child => { %>
        <!-- 递归调用自身模板渲染子评论 -->
        <% include ./comment.ejs %>
      <% }) %>
    </div>
  <% } %>
</div>

步骤2.2 在主模板中调用递归模板

比如你的主模板index.ejs里,只需要循环顶级评论并引入上面的部分模板:

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 可选:添加样式让层级更直观 */
    .comment {
      margin: 10px 0;
      padding: 12px;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
    }
    .comment-replies {
      margin-left: 25px;
      margin-top: 8px;
    }
  </style>
</head>
<body>
  <div class="comments-wrapper">
    <% comments.forEach(topLevelComment => { %>
      <% include ./comment.ejs %>
    <% }) %>
  </div>
</body>
</html>

替代方案:不用部分模板,直接写递归函数

如果不想拆分模板,也可以在主模板里定义一个递归函数来渲染评论:

<!DOCTYPE html>
<html>
<head>
  <!-- 同上的样式 -->
</head>
<body>
  <% // 定义递归渲染函数 %>
  <% function renderComment(comment) { %>
    <div class="comment">
      <div><%= comment.content %></div>
      <% if (comment.children && comment.children.length) { %>
        <div class="comment-replies">
          <% comment.children.forEach(child => renderComment(child)) %>
        </div>
      <% } %>
    </div>
  <% } %>

  <div class="comments-wrapper">
    <% comments.forEach(comment => renderComment(comment)) %>
  </div>
</body>
</html>

这样不管你的评论嵌套多少层(回复的回复的回复...),都能自动生成对应的层级Div结构,完全符合你要的效果。

内容的提问来源于stack exchange,提问作者Nenad Nikoloski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:31