
在 Express.js 中使用 Handlebars 渲染 MongoDB 查询返回的嵌套数组(如 station.Fuel)时,若模板中 {{#each station.Fuel}} 无法显示内容,通常是因为错误地使用了 this. 前缀访问数组元素属性——Handlebars 的 #each 上下文已自动切换为当前迭代项,直接写 {{type}} 即可。
在 express.js 中使用 handlebars 渲染 mongodb 查询返回的嵌套数组(如 `station.fuel`)时,若模板中 `{{#each station.fuel}}` 无法显示内容,通常是因为错误地使用了 `this.` 前缀访问数组元素属性——handlebars 的 `#each` 上下文已自动切换为当前迭代项,直接写 `{{type}}` 即可。
Handlebars 的 {{#each}} 助手在遍历数组时,会将每次迭代的当前元素设为当前上下文(context),因此无需通过 this 显式引用。你当前模板中的写法:
{{#each station.Fuel}}
<h4>Type: {{this.type}}, Price: {{this.price}}, Remaining: {{this.remaining}}</h4>
{{/each}}
虽然语法上不报错,但 this.type 实际等价于 this.this.type(因 this 已是燃料对象本身),导致属性访问失败,最终渲染为空。
✅ 正确写法应省略 this.,直接使用属性名:
{{#each station.Fuel}}
<h4>Type: {{type}}, Price: {{price}}, Remaining: {{remaining}}</h4>
{{/each}}
这样,Handlebars 会在当前迭代项(即 { type: 'Premium', price: 1.97, remaining: 100 } 这样的对象)上直接查找 type、price 和 remaining 属性,确保数据正常渲染。
? 额外建议与注意事项:
- 若数组可能为空或未定义,建议添加安全检查,避免模板崩溃:
{{#if station.Fuel}} {{#each station.Fuel}} <p>Type: {{type}} | Price: {{price}} QR | Stock: {{remaining}} L</p> {{/each}} {{else}} <p>No fuel data available.</p> {{/if}} - 在开发阶段,可在模板中临时调试上下文:
{{log station.Fuel}}(需在 Express 中启用handlebars-helpers或自定义 helper)或通过{{json station.Fuel}}输出 JSON 结构(需注册jsonhelper)。 - 确保 Mongoose Schema 中
Fuel字段未被设为select: false或因.lean()之外的查询选项意外过滤。
掌握这一上下文切换机制,不仅能解决数组渲染问题,也是编写健壮 Handlebars 模板的关键基础。










