Viet
Viet

Reputation: 3387

Rendered template is not loading relevant model

Relevant information

Say I have a Categories model that contains a list of categories. I would like to render this at the Application level to be used as navigation.

Here is what I have

# templates/application.hbs
{{ render categories }}
{{ outlet }}

# templates/categories.hbs
<h1>Categories</h1>
{{#each category in controller}}
    {{#link-to 'category' category}}
        {{category.title}}
    {{/link-to}}
{{/each}}

# routes/categories.js.coffee
App.CategoriesRoute = Ember.Route.extend
    model: ->
        @store.find 'category'

# models/category.js.coffee
App.Category = DS.Model.extend
    title: DS.attr('string'),
    slug: DS.attr('string')

# router.js.coffee
App.Router.map ->
    @resource 'categories', path: 'categories'
    @resource 'category', path: 'category/:slug'

Accessing the /#/categories path renders what I expect; a double of headings and the list of links, each pointing to a category.

If I access the root of the app (Application.Index) at '/', I am expecting to see the same result, albeit only a single rendering of a list of links. However, what results is just the single heading and no links. Using the Ember Inspector, it looks like there isn't a model tied to the {{ render categories }}.

From my understanding, rendering a template will use the relevant controller and view. What would be the correct way to bind the relevant model to the rendered template? Or better yet, what would be the best practice to achieve the same result?

Upvotes: 0

Views: 181

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

When you call {{render categories}}, it will render the categories template with the categories controller. The CategoriesRoute is only used when going to the categories route in the url. In order to have the categories information available at the application level you will need to fetch the categories at that level and store it on the application controller somewhere for use when you render.

 // controller would be application controller, and technically you wouldn't need to write controller
 {{ render 'categories' controller.categories }}  

http://emberjs.jsbin.com/IleQEFa/1/edit

In the example I'm attaching an additional set of models under the name someitems on the application controller. I'm doing this during the setupController, this is the hook that's fired after the model has been resolved in that route.

For you, in the setupController I'd do something like

 this.store.find('category').then( function(records){ controller.set('categories', records)});

or maybe this, I'm not familiar with coffeescript

 @store.find("category").then (records) ->
   controller.set "categories", records

Upvotes: 1

Related Questions