简体   繁体   中英

How to pass models to Ember.js view / application template?

I'm trying to build my app's navigation dynamically based on model data.

In my application template, I'm including a view for the navigation:

<div class="container">
  <h1>My App</h1>
  {{view App.NavView}}
</div>

Here's App.NavView :

App.NavView = Ember.View.extend({
  templateName: 'nav'
});

And the nav template:

<ul class="nav">
  {{#each contentTypes}}
    <li><a href="#">{{name}}</a></li>
  {{/each}}
</ul>

As you can see, I want to loop over contentTypes and display the name of each. Getting these Ember Data models is simple:

App.ContentType.find()

But where do I put this call so that my NavView / nav template has access to the array of models? Should NavView make the call? Or do I make them available to the application template? How?

Thanks for your help!

You can do this using the {{render}} helper . You can either use defaults that the corresponding controller would provide or pass in a model along with the context.

{{render}} is similar to {{outlet}} but you provide the context.

The markup changes to,

<div class="container">
<h1>My App</h1>
{{render 'contentTypes'}}
</div> 

And I added a corresponding contentTypes template

<script type='text/x-handlebars' data-template-name='contentTypes'>
<ul class="nav">
  {{#each contentTypes}}
    <li><a href="#">{{name}}</a></li>
  {{/each}}
</ul>
</script>

Here's a Jsbin example with the contentTypes hardcoded on a ContentTypesController . Your implementation would have contentTypes coming via the model.

You can pass the context to the rendered view into a target outlet with the {{#link-to}} helper in your {{#each}} block, like so:

<script type='text/x-handlebars' data-template-name='contentTypes'>
<ul class="nav">
  {{#each contentTypes}}
    <li>{{#link-to "routeName" this}}{{name}}{{/link-to}}</li>
  {{/each}}
</ul>
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM