Multiple Base Templates in Django

I’ve been working on a pretty big project at work that’s heavily oriented towards mobile devices. We have a Django site running with a lot of custom ecommerce code, but wanted to serve up an optimized experience for mobile devices.

There are a lot of ways to do this, but ultimately we wanted to serve up a different base template for visitors on small-screen mobile devices. We wrote a piece custom view middleware that sets request['is_mobile'] = True. Unfortunately, Django currently requires any {% extends %} template tag to be the first tag in your template. This means you can’t do something like this:

{% if request.is_mobile %}
    {% extends 'mobile_base.html' %}
{% else %}
    {% extends 'default_base.html' %}
{% endif %}

After racking my brain all day my coworker suggested trying the yesno template filter. It worked like a charm!

{% extends request.is_mobile|yesno:"mobile_base.html,default_base.html" %}

So in our view templates we now do {% extends 'base.html' %} which then loads the proper base template depending on the status of is_mobile.