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

1

8

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?

Megara answered 19/4, 2012 at 18:44 Comment(0)
T
17

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 :)

Tiffanytiffi answered 19/4, 2012 at 20:35 Comment(3)
I'll just add to this that using the tryHandlebarsjs.com site (paste in some JSON and your template) can be one of the fastest ways to figure out what's going wrong in this case. Then you're just focused on your template and the data in the absence of anything else that can go wrong.Gumbotil
@Paperwork: Thanks again. I was wondering what the delay was, and now it appears that my question inspired you to sign up for StackOverflow, so I guess we've both done a good deed today :-)Megara
But how to use {{#with object}} only when a property of object is truthy?Annabel

© 2022 - 2024 — McMap. All rights reserved.