Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

flask commands to activate/deactivate a class in Bootstrap

Ok guys, here is my issue when developing my app with flask.

I have a layout.html file which is a simple Bootstrap template basically.

I have a navigation list with a few elements, but let's consider the first 2 just to keep it super simple.

<ul class="nav navbar-nav navbar-right">
    <li {{ home_active }}><a href="/">Home</a></li>
    <li {{ places_active }}><a href="/places">Places</a></li> 
</ul>

To insert class="active", so that the nav item is highlighted after clicking on it I have come out with the above solution: the 2 <li> are my edits. In the app.py I placed this code:

@app.route('/')
@app.route('/home')
def index():
    return render_template('index.html', home_active="class=active")

@app.route('/places')
def map():
    return render_template('places.html', places_active="class=active")

I am decently happy at the moment as things are working as I wanted after quiet a number of tries, but I am pretty sure this way of sorting this problem is terrible: I had to write so much code for such a little thing.

Do you guys know a better way to deal with this?

If so, kindly let me know!

Ty

Vittorio

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher
def some_view():
    return render_template('template.html', active='home')
<li class="{% if active=='home' %}active{%endif %}">Home</li>
<li class="{% if active=='blog' %}active{%endif %}">Blog</li>

Might be a cleaner way to handle it.

Oh niiiice,

I can't believe I did not think about this..

ty Kenneth