[Fixed]-Django: specifying a base template by directory

20👍

May be I oversee something, but all you want can be accomplished with the django template system. All extends calls are relative to template directories.

  1. In order for all base.html files in subdirectories to extend base.html, you just have to put a {% extends "base.html" %} into the files. section1/base.html would would look like that.

    {% extends "base.html" %}

    {# ... rest of your code ...#}

  2. Now, to get the files from section1 to extend section1/base.html you just have to put {% extends "section1/base.html" %} at the top of them. Same for section2, section3 and so on.

It is just that simple, but might not totally obvious in the documentation.

I hope, I understood your question.

5👍

The accepted answer will work, but I do recommend using variable names to keep track of section structure. My personal preference would be a context processor. If, for example, your site’s section organization is transparently reflected in the url, try something like:

# It may be convenient to make this function live in or near your url conf.
def convert_url_path_to_folder_path(path):
    # fill in the magic here

def sub_folder_available(request):
    folder = convert_url_path_to_folder_path(request.path)
    return {'subsection': folder, 'local_base':folder+'/base.html'}

Then in your template, just call

{% extends local_base %}

There are probably a dozen other ways to do this, but the main thing is to think about avoiding hard-coding the folder name into the template. This will get you a lot of mileage, especially since you can just drag and drop template between sections if they happen to be similar enough. Another thing you might add insert is:

def sub_folder_available(request):
    folder = convert_url_path_to_folder_path(request.path)
    # Check if local base exists:
    if os.access(folder+'/base.html',os.F_OK):
        base = folder+'/base.html'
    else:
        # revert to your global base
        base = 'base.html'
    return {'subsection': folder, 'base':base}

The nice advantage of this strategy is of course that you can get a fly-weight section up and running without any local base template at all.

0👍

You can use this library: https://github.com/vb64/django.templates.relative.path

Just write in your templates as follows:

{% load relative_path %}
{% extends “.base.html” %}

this will extend template “base.html”, located in the same folder, where your template placed

{% load relative_path %}
{% extends “…base.html” %}

extend template “base.html”, located at two levels higher

same things works with ‘include’ tag.

Leave a comment