Parseltongue
Parseltongue

Reputation: 11677

Include a .html file in Django template that is located in a different directory

Let's say I have the following directory structure

|-data
    |-include_this.html
|-app
  |- templates
    |- app 
       |- page.html 

In page.html, I'd like to include the include_this.html file contained in the data folder.

I have tried the following:

{% include '../data/include_this.html' %}
{% include '../../data/include_this.html' %}
{% include './../data/include_this.html' %}

But none of them seem to work, and the second one throws the error: The relative path points outside the file hierarchy that template is in.

Re: @Edoardo Facchinelli suggestions, I've modified settings.py in the following way:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'data')],
    'APP_DIRS': True,
}]

But the include_this.html is still not being recognized.

Running

python manage.py shell
from django.conf import settings
print(settings.TEMPLATES[0]['DIRS'])

Returns:

['_templates']

So it's clearly not adding the data directory specified. What's the correct way to do this?

Upvotes: 1

Views: 4388

Answers (1)

Edoardo Facchinelli
Edoardo Facchinelli

Reputation: 422

You need to make sure that the path is known to Django, either as an app, or in this case a template dir. One way to do this is explained here that I think is done well, from that page here's a snippet for the settings.py file, enabling the templates dir.

TEMPLATES = [
      {
       ...
       'DIRS': [os.path.join(BASE_DIR, 'templates')],
       'APP_DIRS': True,
       ...

With other configurations you may need instead the TEMPLATE_DIRS variable, but that will depend on your project, mine use the method in the snippet above.

Once set up, Django will know what data means and you should be able to reference it like so:

{% include 'data/papercups.html' %}

Upvotes: 2

Related Questions