Pug模板/混入无法分离插入数据:如何单独渲染每个Symbol?
问题与解决方案
问题描述
我正在学习Node.js和Pug,当前项目中希望将每个股票代码(Symbol)渲染在独立的行和专属元素中,但所有内容都被塞入同一个<p>标签,完全无法实现预期效果,不知该查找什么内容来解决该问题。
原代码
控制器代码
exports.getAllSymbols = async (req, res, next) => { 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++) { options.testData.push(x.data.data[y].symbol); } res.status(200).render("base", { StockName: stock, StockSym: options.testData, }); };
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 mixin symbol(text) div p #{StockSym} // header include _header .parameters p symbol p RSI p Stoch p StochRSI p MACD .syms //- p #{StockName} //- p #{StockSym} //- p #{test} +symbol() // FOOTER include _footer script(src="/scripts/script.js")
解决方案
1. 修复控制器代码(避免全局数据污染)
原代码使用全局数组options.testData存储股票代码,会导致多次请求后数据累加。改成每次请求生成独立数组:
exports.getAllSymbols = async (req, res, next) => { const response = await axios.get(options.allStocksURL, options.allStockOptions); const stockData = response.data.data; // 用map直接提取所有股票代码,生成独立数组 const stockSymbols = stockData.map(item => item.symbol); // 保留原有逻辑取第一个股票名称 const firstStockName = stockData[0]?.name || ''; res.status(200).render("base", { StockName: firstStockName, StockSym: stockSymbols, }); };
2. 修改Pug模板(遍历数组渲染独立元素)
原mixin直接输出整个数组,导致所有符号挤在一个<p>里。需要用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 // 定义mixin接收单个股票代码参数 mixin symbol(sym) div.symbol-item p #{sym} include _header .parameters p symbol p RSI p Stoch p StochRSI p MACD .syms // 遍历StockSym数组,逐个调用mixin渲染 each sym in StockSym +symbol(sym) include _footer script(src="/scripts/script.js")
关键问题点说明
- 控制器端:全局数组会导致跨请求数据污染,每次请求必须生成独立的数据集。
- Pug端:直接输出数组会被转为字符串,必须用
each循环遍历数组,才能为每个元素创建独立的DOM节点。
内容的提问来源于stack exchange,提问作者scorpio
相关产品推荐
相关产品推荐

