EJS中speakerNames变量未定义求助:如何遍历数组渲染下拉菜单
问题分析与解决方案
你遇到的核心问题是中间件注册顺序错误,导致路由处理请求时,设置speakerNames的中间件还未执行,因此EJS模板无法读取到该变量。
关键原因
Express中间件按注册顺序执行,如果你的路由(比如router.get('/'))先于设置response.locals.speakerNames的中间件被注册,请求进入路由处理逻辑时,中间件还没来得及给locals赋值,模板自然会提示变量未定义。
解决步骤
调整中间件与路由的注册顺序
将设置speakerNames的全局中间件,放在所有路由注册代码的前面。示例如下:// 先注册全局中间件 app.use(async (request, response, next) => { try { const names = await speakersService.getNames(); response.locals.speakerNames = names; console.log(response.locals); return next(); } catch (error) { console.error(error); return next(error); } }); // 再注册路由 const mainRouter = require('./path/to/your/router'); // 替换为你的路由文件路径 app.use(mainRouter);验证路由中的locals值
在首页路由里添加打印,确认speakerNames是否已被赋值:router.get('/', async (request, response) => { const topSpeakers = await speakersService.getList(); console.log('路由中的locals:', response.locals); // 查看是否包含speakerNames response.render('layout', { pageTitle: 'Welcome', template: 'index', topSpeakers }); });模板兜底处理(可选)
为避免因数据加载失败导致模板报错,可在EJS中添加存在性判断:<% if (speakerNames && speakerNames.length) { %> <% speakerNames.forEach(function(speaker) { %> <a class="dropdown-item" href="/speakers/<%=speaker.shortname%>"> <%=speaker.name%> </a> <% }) %> <% } %>
内容的提问来源于stack exchange,提问作者Narendra Singh
相关产品推荐
相关产品推荐

