Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars nested objects

I am using backbone.js with nested models. The idea being self-contain all attributes of the author as well as to re-use the author model on both posts and comments. At least in theory this makes sense I would think.

However, setting things up like this I've run into a confusion how to retrieve the different values with Handlebars. Handlebars doesn't like being passed objects from what I've read. I can easily retrieve the status in a {{#each}} with {{status}} but naturally doing {{author.name}} won't work.

I've looked at using a Helper, however as you can see I have comments nested inside, that will have another author nested inside. I don't believe helpers inside helpers will work.

This is a sample object pulled from the console of Chrome.

Object {items: Array[2]}
    +items: Array[2]
        +0: Object
            +author: child
                _changing: false
                _pending: false
                _previousAttributes: Object
                +attributes: Object
                    name: "Amy Pond"
                    profileImage: "Amy.jpg"
                    __proto__: Object
                changed: Object
                cid: "c0"
                __proto__: Surrogate
            comments: child
            id: "50f5f5d4014e045f000001"
            status: "1- This is a sample message."
            __proto__: Object
        +1: Object
            author: child
            comments: child
            id: "50f5f5d4014e045f000002"
            status: "2- This is another sample message."
            __proto__: Object
            length: 2
            __proto__: Array[0]
            __proto__: Object

Am I incorrect in my organization, or is there a better way to handle multidimensional data? Or is there a nice way for Handlebars to get to each of the values?

If there is a more powerful templating engine, I'm open options.

like image 506
Sir.Nathan Stassen Avatar asked Aug 20 '13 17:08

Sir.Nathan Stassen


1 Answers

Seems the problem is that you put the Backbone model directly into your template, but you have to convert it into a JSON object first using model.toJSON(). Or you try to access author.attributes.name.

From the docs:

Handlebars also supports nested paths, making it possible to look up properties nested below the current context.

<div class="entry">
  <h1>{{title}}</h1>
  <h2>By {{author.name}}</h2>

  <div class="body">
    {{body}}
  </div>
</div>

That template works with this context

var context = {
  title: "My First Blog Post!",
  author: {
    id: 47,
    name: "Yehuda Katz"
  },
  body: "My first post. Wheeeee!"
};
like image 96
Andreas Köberle Avatar answered Sep 28 '22 08:09

Andreas Köberle