Search code examples
ember.jsember-router

Understanding Ember routes


Assume I have routemap like this:

App.Router.map ->
    @resource 'posts', ->
        @resource 'post', {path: '/:post_id'}

So I have list of posts on /posts route and a single post on posts/2. By default posts template will be rendered to {{outlet}} of a parent template (application) which is OK and post template to {{outlet}} of posts template which is not what I want. I want to replace list of posts with a single post.

So I came with that solution to set desired template to render to it's {{outlet}}:

App.PostRoute = Em.Route.extend
    renderTemplate: ->
        this.render(into: 'application')

But as a result I have list of posts and a single post rendered into one {{outlet}}. I can emtpy {{outlet}} each new route but then it breaks back button, cuz Ember wont render previous template again, assuming that is already rendered.

So questions is how to use single {{outlet}} for different routes and don't break ember's logic. Of course I can avoid nested routes but they a really usefull when you need semantic links like this post/2/comment/12/edit.


Solution

  • If your templates are not nested, you shouldn't nest your routes, or you'll end up fighting Ember. Acting as Ember's state manager, routes describe your app structure. Nesting should follow your UI, not how you want your URLs to look like.

    If your concern is URLs, you can just modify the path to fit your needs:

    App.Router.map ->
      @resource 'posts'
      @resource 'post', { path: 'posts/:post_id' }