Node.js中Axios数据在Pug模板无法按元素拆分显示求助
问题
在Udemy课程练习Node.js+Pug模板引擎时,想要为每条传入的数据生成独立卡片,但当前代码将Axios请求返回的所有数据放入单个元素中,无法生成独立元素。
控制器代码
exports.getAllSymbols = async (req, res, next) => { let data = []; const x = await axios.get(options.allStocksURL, options.allStockOptions); const stocks = await x.data.data[0]; const stock = x.data.data[0].name; const symbol = stocks.symbol.toString(); for (let y = 0; y <= x.data.data.length - 1; y++) { data.push(x.data.data[y].symbol); } res.status(200).render("base", { StockName: stock, StockSym: data, }); };
Pug模板代码
html head meta(charset='UTF-8') meta(name='viewport', content='width=device-width', initial-scale='1.0') link(rel='stylesheet', href='/css/style.css') link(rel='shortcut icon', type='image/png', href='/img/favicon.png') link(rel='stylesheet', href='https://fonts.googleapis.com/css?family=Lato:300,300i,700') title Dashboard | #{title} body // header include _header //- CONTENT block content div h3 #{StockName} h3 (#{StockSym})
解决方案
1. 修正控制器:传递完整股票数据集
当前控制器仅传递了第一个股票的名称和所有股票的代码数组,无法为每个股票匹配对应名称。应直接传递所有股票的完整数据集合:
exports.getAllSymbols = async (req, res, next) => { try { const response = await axios.get(options.allStocksURL, options.allStockOptions); const stocks = response.data.data; res.status(200).render("base", { stocks: stocks, title: "Stock Dashboard" }); } catch (err) { next(err); } };
2. 修改Pug模板:循环生成独立卡片
使用Pug的each循环遍历股票数组,为每条数据生成独立的卡片元素:
html head meta(charset='UTF-8') meta(name='viewport', content='width=device-width', initial-scale='1.0') link(rel='stylesheet', href='/css/style.css') link(rel='shortcut icon', type='image/png', href='/img/favicon.png') link(rel='stylesheet', href='https://fonts.googleapis.com/css?family=Lato:300,300i,700') title Dashboard | #{title} body // header include _header //- CONTENT block content .stock-cards each stock in stocks .stock-card h3 #{stock.name} p (#{stock.symbol})
核心要点
- 控制器传递完整的股票数组,让模板能访问每个股票的所有字段
- Pug的
each语法是实现批量生成独立元素的关键,通过它遍历数组并重复渲染卡片结构 - 添加错误捕获逻辑,避免请求失败导致程序异常
内容的提问来源于stack exchange,提问作者scorpio
相关产品推荐
相关产品推荐

