I am building my first web application with twitter bootstrap and I am liking it, but I am running into a problem of repeating myself.
I am building a navigation bar, and I want the UI to reflect which tab is active based on the url. I am using backbone to route the urls. The only problem is that I have to manually code a bunch of different variables to be “active” or “” based on the url so that the tabs will reflect the appropriate state.
<template name="navbar">
<div class="container">
<div class="row">
<div class="span6">
<ul class="nav nav-tabs">
<li class="{{home}}">
<a href="/home/">Home</a></li>
<li class="{{1999s10}}{{1965malibu}}{{1960hearse}}{{1966gto}}{{1971blazer}} dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Cars<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="{{1999s10}}"><a href="/cars/1999s10">1999 Electric S-10</a></li>
<li class="{{1965malibu}}"><a href="/cars/1965malibu">1965 Malibu</a></li>
<li class="{{1960hearse}}"><a href="/cars/1960hearse">1960 Hearse</a></li>
<li class="{{1966gto}}"><a href="/cars/1966gto">1966 GTO</a></li>
<li class="{{1971blazer}}"><a href="/cars/1971blazer">1971 Bazer</a></li>
<!-- <li class="divider"></li> -->
</ul>
</li>
</div>
</div>
</div>
As you can see, right now, I have a bunch of variables for indicating what tabs are active. I have started to implement the following code, but Its so inelegant that I have stopped and want to use a better method.
Template.navbar.home = function () {
return Session.equals("active", "home") ? "active" : '';
};
// a bunch more of these for every route
var TodosRouter = Backbone.Router.extend({
routes: {
"home/": "home",
// more routes
},
home: function () {
Session.set("active", "home");
},
// more functions for capturing the routes and setting the session variable "active"
});
Router = new TodosRouter;
Meteor.startup(function () {
Backbone.history.start({pushState: true});
});
Using this method:
(1) has the issue of variables that start with numbers (my bad)
(2) requires me to route every url to change the Session “active” variable accordingly
(3) requires me to make a template handler for every button/url in the navigation bar
There has to be a better method for doing this, but I have yet to find it.
To reiterate, I want to find a way of accomplish activating the necessary tabs without breaking the DRY (do not repeat yourself) programming principle.
edit:
What would be really nice is something like this:
<li class="{{(url=="/cars/1999s10/")?"active":""}}"><a href="/cars/1999s10">1999 Electric S-10</a></li>
That would be a minimal amount of code.
I found out something that works:
and in the html, the ” vs ‘ is crucial!
this works, but my only concern is the using the router for other urls later…