I'm using Twitter Bootstrap for navigation in my Ember.js app. Bootstrap uses an active
class on the li
tag that wraps navigation links, rather than setting the active
class on the link itself.
Ember.js's new linkTo
helper will set an active
class on the link but (as far as I can see) doesn't offer any to hook on to that property.
Right now, I'm using this ugly approach:
{{#linkTo "inbox" tagName="li"}} <a {{bindAttr href="view.href"}}>Inbox</a> {{/linkTo}}
This will output:
<li class="active" href="/inbox"><a href="/inbox">Inbox</a></li>
Which is what I want, but is not valid HTML.
I also tried binding to the generated LinkView's active
property from the parent view, but if you do that, the parent view will be rendered twice before it is inserted which triggers an error.
Apart from manually recreating the logic used internally by the linkTo
helper to assign the active
class to the link, is there a better way to achieve this effect?
We definitely need a more public, permanent solution, but something like this should work for now.
The template:
<ul> {{#view App.NavView}} {{#linkTo "about"}}About{{/linkTo}} {{/view}} {{#view App.NavView}} {{#linkTo "contacts"}}Contacts{{/linkTo}} {{/view}} </ul>
The view definition:
App.NavView = Ember.View.extend({ tagName: 'li', classNameBindings: ['active'], active: function() { return this.get('childViews.firstObject.active'); }.property() });
This relies on a couple of constraints:
<li>
s. There's a lot of detail in the docs about how to customize a view's element from its JavaScript definition or from Handlebars.I have supplied a live JSBin of this working.
Well I took what @alexspeller great idea and converted it to ember-cli:
app/components/link-li.js
export default Em.Component.extend({ tagName: 'li', classNameBindings: ['active'], active: function() { return this.get('childViews').anyBy('active'); }.property('[email protected]') });
In my navbar I have:
{{#link-li}} {{#link-to "squares.index"}}Squares{{/link-to}} {{/link-li}} {{#link-li}} {{#link-to "games.index"}}Games{{/link-to}} {{/link-li}} {{#link-li}} {{#link-to "about"}}About{{/link-to}} {{/link-li}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With