Cléber Zavadniak Website

Django templates are like classes

A common mistake I see when working with Django projects is thinking about templates as something different than code when, in reality, good practices from one world (coding) should also be applied to the other (templates).

Django templates are like classes: instead of writing one big function with a lot of “ifs” inside it or many similar functions with lots of shared code, you should make good use of classes and inheritance and gather all common behavior in base classes while implementing specific ones in children of these. So, instead of writing a big template with a lot of “ifs” inside it or many similar templates with lots of shared markup and code, you should make good use of template extending and gather all common behavior in base templates while implementing specific ones in children of these.


Let’s say your system has one screen with user settings but has also two kinds of users: regular ones and administrators. The later ones have many more options than the first, so it’s tempting to have only one template with a big chunk of markup under a if user is admin or even copying the user/settings.html template into user/admin/settings.html and loading one or another depending on the user profile.

Both options are terrible because (1) you’d be implementing different behaviors in only one “function” or (2) you’d be repeating a lot of code.

A better approach would be to create a users/settings/base.html that implements the most basic settings and then extending it in both users/settings/regular-user.html and users/settings/admin.html.

And, yes, regular-user.html probably would have nothing different than the base template it extends, but at least (1) you have a stupidly obvious place to implement regular-user specific features (and it’s very likely you’ll need it later on the project) and (2) it becomes stupidly obvious that base.html is a base “class” and NOT intended specifically to the regular user itself (what’s very good, since there’s always the probability that someone, sometime, will be very lazy and, instead of creating the regular-user.html extended template, will simply put a damned if in the base template and make everything confusing as hell).

So, in short, if you think about your Django templates as classes and as regular code, you’ll be taking advantage of many, MANY!, years of learning of thousands of people about the art of coding and your life will become much easier.

Resist the temptation to think about templates as “a minor issue”, a small and unimportant detail. It’s still a kind of code and it also should be clean.

Back to index