Bootstrap Menus and EmberJS

I love Bootstrap. Mostly because I'm not a very good graphic designer; but also because I'm lazy. I like the things it does for me that make my websites suck less. One of those things is the Bootstrap menu.
One of the nice features of the Bootstrap menu is that you get a gradient highlight when the menu has a "selected" css class applied to it.

I am looking at EmberJS. Ember has lots of nifty features as well. As a Single Page Application (SPA) framework, it likes to handle URL routing, and does something especially nifty with links that it manages: It applies a "selected" class to the current URL.

Did the stars just align? Is this too good to be true? "Um, yea. Why?"

Well, they almost align. It turns out that Bootstrap wants to have a "selected" css class applied to the list item that contains the anchor tag for the menu item while Ember's linkTo helper applies it directly to the anchor tag. Ouch.

In other words, this ember code doesn't work
<li>{{#linkTo "home"}}home{{/linkto}}</li>
What you end up with is html that looks like this
<li><a href='#home' class='selected'>home</a></li>
Unless we want to change bootstrap (again, did I mention that I'm lazy), what we really want is something that looks like this
<li class='selected'><a href='#home'>home</a></li>
Well, it turns out that the ember linkTo block helper can be manipulated to work with bootstrap.
{{#linkTo "home" tagName="li" href=false}}<a {{bindAttr href="view.href" }}>Home</a>{{/linkTo}} 
What this little gem does is override the tag name for the linkTo helper, and tell it not to have a href property. Then, inside the anchor tag, we reconstruct the link using the href property from the containing view.

Comments

Popular posts from this blog

Database Projects, SQL Unit Tests, and TeamCity

Brent: Programmer. Gamer. Cheapskate. All around good guy.

Building nice XML from SQL Server Tables