You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Handlebars模板中正确调用工厂函数的getPerson方法?

解决Handlebars中调用对象方法渲染数据的报错问题

问题原因

Handlebars的模板表达式语法不支持直接使用()调用方法,你写的{{this.getPerson().theName}}违反了它的语法规则,这就是报错“Expecting 'ID', got 'INVALID'”的直接原因。

可行解决方案

1. 提前预处理数据(最简单直接)

在将数据传入Handlebars模板之前,先遍历allPeople数组,调用每个对象的getPerson()方法提取出需要的属性,生成一个纯数据数组:

// 预处理:提取所有Person的实际数据
const processedPeople = allPeople.map(person => person.getPerson());

// 渲染模板时传入处理后的数组
const template = Handlebars.compile(document.getElementById('your-template').innerHTML);
document.getElementById('target').innerHTML = template({ people: processedPeople });

模板中直接访问属性即可:

{{#each people}}
  <div>姓名: {{theName}}, 年龄: {{age}}</div>
{{/each}}

2. 自定义Handlebars辅助函数

如果需要保留原对象的方法调用逻辑,可注册一个辅助函数来封装方法调用:

// 注册辅助函数:调用getPerson并返回指定属性
Handlebars.registerHelper('getPersonProp', function(person, propName) {
  return person.getPerson()[propName];
});

模板中使用辅助函数:

{{#each people}}
  <div>姓名: {{getPersonProp this "theName"}}, 年龄: {{getPersonProp this "age"}}</div>
{{/each}}

或者注册一个返回完整数据对象的辅助函数,配合{{#with}}使用:

Handlebars.registerHelper('getPerson', function(person) {
  return person.getPerson();
});

模板写法:

{{#each people}}
  {{#with (getPerson this)}}
    <div>姓名: {{theName}}, 年龄: {{age}}</div>
  {{/with}}
{{/each}}

3. 改造Person工厂函数(添加getter属性)

如果允许修改工厂函数,可以为返回的对象添加getter属性,让模板能直接访问内部数据,无需调用方法:

function Person(name, age) {
  const theName = name;
  const personAge = age;

  return {
    getPerson() {
      return { theName, age: personAge };
    },
    // 添加getter,模拟直接属性访问
    get theName() {
      return theName;
    },
    get age() {
      return personAge;
    }
  };
}

模板中直接访问属性:

{{#each people}}
  <div>姓名: {{theName}}, 年龄: {{age}}</div>
{{/each}}

内容的提问来源于stack exchange,提问作者Keith Rubin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:35:11