7

I have a template

<template name='order'>
  {{vendor.name}}
</template>

rendered with

  Template.order.vendor = function () {
    return {name: 'Chanel', address: 'Paris' };
  };

When I try to access this.data in

Template.order.rendered = function () {
  console.log(this.data);
};

I get 'undefined'.

What is the correct way of getting e.g. vendor.name and vendor.address in Template.order.rendered?

Thank you.

4

2 回答 2

4

在 Template.rendered 中,this.data 对应于模板“馈送”的数据,作为参数或使用 {{#with}} 构造。vendor 只是一个帮助函数,返回订单模板中可用的数据,但未绑定到“this.data”。所以要解决您的问题,您有多种选择:

定义父模板并将供应商助手移动到此父模板,然后您可以选择以供应商作为参数调用订单或使用 {{#with 块}}

<template name="parent">
    {{> order vendor}}
    {{#with vendor}}
        {{> order}}
    {{/with}}
</template>

<template name="order">
    {{name}}
</template>

Template.parent.vendor=function(){
    return{
        name:"Chanel",
        address:"Paris"
    };
};

Template.order.rendered=function(){
    // this.data == vendor object returned in parent helper
    console.log(this.data);
};

您还可以注册一个全局助手,从而无需封装父模板:

Handlebars.registerHelper("vendor",function(){
    return{
        name:"Chanel",
        address:"Paris"
    };
});
于 2013-07-17T11:04:44.333 回答
0
Template.order.rendered = function () {
    console.log(Template.order.vendor());
}
于 2013-07-17T10:56:51.953 回答