Tidbits | Aug. 8, 2016

Pro-Tip – Extend Django Templates Smartly

by Jeff Triplett |   More posts by Jeff

One of my all favorite template tricks goes back to my LJ World days.

Most people don't realize that the extends tag accepts a variable and not just a hard-coded literal value. This allows for magical things to happen when combined with a default.

The following block extends a base template named "base.html" if the base_template is not set.

{% extends base_template|default:"base.html" %}

For any page that you want to programmatically override the base template, you may do so by adding a base_template context variable to your views context values which are exposed to your template.

from django.views.generic import TemplateView


class MarketingView(TemplateView):

    template_name = 'marketing_landing.html'

    def get_context_data(self, **kwargs):
        context = super(MarketingView, self).get_context_data(**kwargs)
        context['base_template'] = 'base_marketing.html'
        return context

This simple trick opens the door to do fun things with your website based on the day of the year or something useful like A/B test two different versions of your website's landing page. The possibilities are endless.


python   django  

You can use a variable to set the name of the template you are extending when using Django templates.

2016-08-08T11:55:49.403558 2016-08-08T16:10:06.318983 2016 python,django