How Do I Access an Object's Properties From a Template?

假如想象 提交于 2019-12-01 00:33:40

问题


According to http://handlebarsjs.com/expressions.html, I should be able to do this:

<h1>{{article.title}}</h1>

But I can't seem to get this to work in meteor. Here's my template:

<template name="content">
  {{#if item}}
    <p>{{item.name}}</p>
  {{/if}}
</template>

Here's the JavaScript that returns the item:

  Template.content.item = function() {
    return Items.findOne({ _id: Session.get("list_id") });
  };

And yes, the item does indeed have a property called name :-)

When I do this, I see an error in Firebug that says ret is undefined

This can be tracked down to evaluate.js:

for (var i = 1; i < id.length; i++)
  // XXX error (and/or unknown key) handling
  ret = ret[id[i]];
return ret; 

At the moment of the error, ret references the window object. What's up with that?


回答1:


You should use {{#with object}}

If your object is something like :

my_object = {
    name : 'my_name',
    prop : 'my_prop'
}

In your template your can do :

<template name="my_template">
    {{#with my_object}}
        <p>Name is {{name}}<p>
        <p>Prop is {{prop}}</p>
    {{/with}}
</template>

Here you go :)



来源:https://stackoverflow.com/questions/10234725/how-do-i-access-an-objects-properties-from-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!