javascriptember.jsember-router

How can I hang the "active" class only on the current route?


I have such routes:

this.route('posts', function() {
  this.route('index', { path: '/' })
  this.route('show', { path: '/:post_path' }, function() {
    this.route('people', { path: '/people' })

    this.route('files', function() {
      this.route('images', { path: '/images' })
      this.route('videos', { path: '/videos' })
    })
  })
}),

I have a problem with the class "active".

Take, for example, this link:

http://localhost:4200/posts/1-best-post/files/images

In this case, the class "active" will hang on two links - on posts.show.files.images and on posts.show.

How to make the class "active" only for posts.show.files.images?

ADDITION

Apparently the problem is not only with the class "active". But with the templates. The children use the "show" template.

Could you please explain how to properly describe such nested routes?


Solution

  • The issue you're encountering is because ember has a hidden index route for each nested function in the router.

    Your route file actually expands out to look like this.

    this.route('posts', function() {
      this.route('index', { path: '/' })
      this.route('show', { path: '/:post_path' }, function() {
        this.route('index', { path: '/' }) #New
        this.route('people', { path: '/people' })
    
        this.route('files', function() {
          this.route('index', { path: '/' }) #New
          this.route('images', { path: '/images' })
          this.route('videos', { path: '/videos' })
        })
      })
    }),
    

    When you define the link-to path, I'm going to assume that you specify it exactly as it looked, rather than using the hidden index.

    # Don't do this
    {{#link-to 'posts.show' "1234"}}Posts Show{{/link-to}}
    {{#link-to 'posts.show.files.images' "1234"}}Images Show{{/link-to}}
    # Do this
    {{#link-to 'posts.show.index' "1234"}}Posts Show{{/link-to}}
    {{#link-to 'posts.show.files.images' "1234"}}Images Show{{/link-to}}
    

    This ember-twiddle shows an example of the issue you're having. The top section shows the issue you're experiencing. The bottom section shows the corrected links.

    Similarly, the show.hbs route you're using is going to be considered a wrapper for ALL routes under show.
    If you don't want the content of show when you're looking at files or images, move the logic and display into posts/show/index.js and posts/show/index.hbs