
在 Express.js + Handlebars 应用中,使用 {{#each}} 迭代数组时若错误地添加 this. 前缀(如 {{this.type}}),会导致模板渲染失败或静默忽略——应直接使用 {{type}} 等属性名访问当前上下文对象。
在 express.js + handlebars 应用中,使用 `{{#each}}` 迭代数组时若错误地添加 `this.` 前缀(如 `{{this.type}}`),会导致模板渲染失败或静默忽略——应直接使用 `{{type}}` 等属性名访问当前上下文对象。
当您在 Handlebars 模板中使用 {{#each station.Fuel}} 时,Handlebars 会自动将每次迭代的当前数组项设为当前上下文(context)。这意味着在块内无需通过 this 显式引用当前对象;直接使用 {{type}}、{{price}}、{{remaining}} 即可正确读取属性值。
✅ 正确写法(推荐):
{{#each station.Fuel}}
<h4>Type: {{type}}, Price: {{price}}, Remaining: {{remaining}}</h4>
{{/each}}
❌ 错误写法(导致渲染为空):
{{#each station.Fuel}}
<h4>Type: {{this.type}}, Price: {{this.price}}, Remaining: {{this.remaining}}</h4>
{{/each}}
⚠️ 注意:Handlebars 的
this在{{#each}}块内仅在需要显式切换上下文(如嵌套{{#with}}或调用辅助函数)时才需谨慎使用;日常属性访问应避免冗余this.—— 这不是语法错误,但this在当前上下文中指向的是整个station.Fuel数组而非单个元素,因此{{this.type}}实际为undefined。
此外,建议增强健壮性:添加空数组兜底处理,防止 station.Fuel 为 null 或 undefined 时模板报错:
{{#if station.Fuel}}
<h3>Current Fuel Prices</h3>
{{#each station.Fuel}}
<h4>Type: {{type}}, Price: {{price}}, Remaining: {{remaining}}</h4>
{{/each}}
{{else}}
<p>No fuel data available.</p>
{{/if}}
总结:Handlebars 的 {{#each}} 是作用域感知型助手,其内部天然绑定当前迭代项,简洁即正确。调试时可通过 {{log this}}(需注册 log 辅助函数)在模板中打印当前上下文,快速验证数据结构与访问路径。










