Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 315
Samo Avatar asked Apr 19 '12 18:04

Samo


People also ask

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

How do you access properties in an array of objects?

We can access the property of an object by using multiple ways that are by using dot, for in loop, map(), array. from(), and reduce() method.

What are object properties in JavaScript?

Object properties are defined as a simple association between name and value. All properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. Properties refer to the collection of values which are associated with the JavaScript object.


1 Answers

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

like image 59
Gabriel Dehan Avatar answered Oct 22 '22 02:10

Gabriel Dehan