0
votes

I'm sending data from my backbone view to a handlebars template (js fiddle: http://jsfiddle.net/8NhjD/) like this:

this.$el.html(this.template({
        users: that.users.toJSON(),
        audiences: that.audiences.toJSON()
}));

and I'm trying to access the list of users and audiences like this:

<select name="user" class = "form-control">
{{#each users}}
    <option value="{{name}}">{{name}}</option>
{{/each}}
</select>

But the dropdown menus for the users and audiences are empty. What am I doing wrong here?

2
good point! jsfiddle.net/8NhjDtldr
Are you really storing your templates in a <div>?mu is too short
@muistooshort - yes, is that not a good practice?tldr
Templates are rarely valid HTML (they're just text that sort of looks like HTML) so you should store them in <script type="text/x-handlebars"> containers to keep the browser's hands off them.mu is too short
wow, good to know. Thanks @muistooshort!tldr

2 Answers

0
votes

Your problem is that you are passing in the models, which do not expose their attributes directly. Try something like this:

this.$el.html(this.template({
        users: that.users.toJSON(),
        audiences: that.audiences.toJSON()
}));

UPDATED:

Without a complete fiddle, it is hard to see where you went wrong. Here is a working fiddle: http://jsfiddle.net/moderndegree/qW7Tz/

HTML:

<script id="thing-template" type="text/x-handlebars-template">
<ul>
    {{#each things}}
    <li>{{this.thing}}</li>
    {{/each}}
</ul>
</script>
<div id="thing-view"></div>

JS:

var ThingModel = Backbone.Model.extend({}),
    ThingCollection = Backbone.Collection.extend({
        model: ThingModel
    }),
    ThingView = Backbone.View.extend({
        el: '#thing-view',
        template: Handlebars.compile($("#thing-template").html()),
        initialize: function(){
            this.things = new ThingCollection([{thing: 'purple'}, {thing: 'monkey'}, {thing: 'dishwasher'}]);
        },
        render: function(){
            console.log(this.things.toJSON());
            this.$el.html(this.template({
                things: this.things.toJSON()
            }));
            return this;
        }
    });
var view = new ThingView().render();
0
votes

Moving the collection-fetching from the view's initialize method to the route-handler resolved the issue.