Read my book

I wrote books about Webpack and React. Check them out!

Wednesday, March 14, 2012

Dealing with Navigation in Django

I've been pretty busy with a surprise project (more on that later). I thought it might be fun to share one handy snippet I came up with during its development. There's no one right way to implement navigation in Django.

My solution utilizes a class (navigation "model") and a minimal include (template within template) that defines the markup. It also makes it easy to use i18n. Instead of boring you further just have a look at the code and let me know what you think. I'm sure there's still some room for improvement. Perhaps this will inspire someone to write something truly superior, or not.

My containing the navigation looks like this:

You'll need to inject an instance of that class to your template context like this: c = {'navi': Navi(request.path)}. You'll also need some template to render it out. Here's one way to do that (includes/navigation.html):

There we go! Now we should have a spiffy little navigation on our site. It's probably quite easy to extend the idea to support nested navigation and whatnot. That's up to you, though.

PS. If you read this via RSS, it's likely the code examples didn't show up. Surf to this post or check out this Gist for code examples.