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

如何在Node.js中动态批量生成jade(Pug)模板元素?

解决方法

1. 调整后端路由参数传递

你不需要单独提取第一篇文章的字段传入模板,直接把完整的文章数组传给模板即可:

router.get('/', function(req, res, next) {
    postInfo.find({}).then((data) => {
        // 直接把全量文章数组传给模板
        res.render('index' , {
            posts: data
        });
    });
});

2. 修改Pug模板使用循环批量生成结构

在Pug模板中使用each迭代语法,遍历传入的posts数组,每一项对应渲染一套你需要的标签结构:

each post in posts
  h2
    a(href=`/${post.postId}`)  #{post.title}
  .content   #{post.content}

渲染后会自动根据数组长度生成对应数量的文章模块,不需要手动重复编写结构。

可选优化:封装为复用组件

如果这套结构在多个页面都需要用到,可以封装为Pug的mixin,方便全局调用:

// 定义mixin
mixin postCard(post)
  h2
    a(href=`/${post.postId}`)  #{post.title}
  .content   #{post.content}

// 调用mixin循环渲染
each post in posts
  +postCard(post)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:24:03