[Answered ]-Change django template search path depending on request

1👍

This is exactly why I’ve created django_layers

It’s inspired by the Plone skinning/layer system where you can switch skins and have the framework search different layers for templates, staticfiles, and so on. I was missing something similar in Django where, like you, the only option I could find was inheritance or distinct INSTALLED_APPS configurations.

It turns out it’s also very suitable for other use-cases such as A/B testing.

The packages is relatively new, let me know if it works for you or if you have issues if you decide to use it.

1👍

You can leverage template inheritance for this purpose, especially the {% extends %} template tag, which can accept variables instead of literal strings.

Example:

In your child templates make them extend unknown base template like this:

{% extends BASE_SITE_TEMPLATE %}

{% block page_head %}
    <!-- Custom per-page static files may be defined here -->
{% endblock %}

{% block page_content %}
    ...
{% endblock %}

And then write a template context processor that will pass the BASE_SITE_TEMPLATE variable based on your custom conditions to rendered templates:

def base_site_template(request):
    # Here goes your conditions to select proper base template, for example
    # by checking request.user permissions or some other logic.
    ...
    return {'BASE_SITE_TEMPLATE': ...}

Of course You will need to define various base templates, like base_site_user.html, base_site_editor.html, base_site_admin.html.

This method doesn’t require you to change any of your views, just child templates, so I think it’s one of the simplest methods to do what You want.

Leave a comment