如何使用Pug/Jade展示外部JSON?求API请求与遍历示例
在Pug模板中遍历API获取的JSON数据
当然可以实现!Pug(原Jade)完全支持遍历从API获取的JSON数据,下面我会一步步演示完整流程,还会对比你熟悉的Handlebars写法,帮你快速上手。
1. 后端发起GET请求并传递数据到Pug
假设你用Express作为后端框架,我们可以用node-fetch或axios发起API请求,把解析后的JSON数据传递给Pug模板:
const express = require('express'); const fetch = require('node-fetch'); const app = express(); // 设置视图引擎为Pug app.set('view engine', 'pug'); app.get('/', async (req, res) => { try { // 发起API GET请求 const apiResponse = await fetch('https://api.example.com/your-endpoint'); const jsonData = await apiResponse.json(); // 解析返回的JSON // 将数据传递给Pug模板(这里把数据命名为`items`) res.render('index', { items: jsonData }); } catch (error) { console.error('API请求失败:', error); // 出错时传递空数组,避免模板报错 res.render('index', { items: [] }); } }); app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));
2. 在Pug模板中遍历JSON数据
Pug的遍历语法是each,比Handlebars的{{#each}}更简洁,我们直接对比来看:
对比Handlebars写法(你熟悉的方式)
{{#each items}}
{{/each}}{{title}}
{{description}}
Pug的等价写法
//- index.pug html head title API数据遍历示例 body h1 从API获取的内容列表 //- 遍历items数组,每个元素命名为item each item in items .item h3= item.title p= item.description //- 当数据为空时显示提示 if items.length === 0 p.empty 暂无可用数据
遍历JSON对象(非数组)
如果API返回的是单个JSON对象(而非数组),你也可以遍历它的键值对:
//- 假设传递的是userInfo对象,比如{name: "张三", age: 28} each value, key in userInfo p #{key}: #{value}
3. 进阶:遍历中的条件判断
你还可以在遍历过程中加入条件筛选,只渲染符合要求的数据:
each item in items //- 只渲染状态为active的项 if item.status === 'active' .item.active h3= item.title p= item.description span.tag 已激活
其实Pug的遍历逻辑和Handlebars核心思路一致,只是语法更简洁,不需要额外的模板标签。只要后端把API数据正确传递到模板上下文,就能轻松实现遍历渲染。
内容的提问来源于stack exchange,提问作者user6347891
相关产品推荐
相关产品推荐

