javascript 如何从模板访问对象的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10234725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Do I Access an Object's Properties From a Template?
提问by Samo
According to http://handlebarsjs.com/expressions.html, I should be able to do this:
根据http://handlebarsjs.com/expressions.html,我应该能够做到这一点:
<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:
这是返回项目的 JavaScript:
Template.content.item = function() {
return Items.findOne({ _id: Session.get("list_id") });
};
And yes, the item does indeed have a property called name
:-)
是的,该项目确实有一个名为name
:-)的属性
When I do this, I see an error in Firebug that says ret is undefined
当我这样做时,我在 Firebug 中看到一个错误,上面写着 ret is undefined
This can be tracked down to evaluate.js:
这可以追溯到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?
在发生错误时,ret
引用window
对象。那是怎么回事?
回答by Gabriel Dehan
You should use {{#with object}}
你应该使用 {{#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 :)
干得好 :)