Loading templates by app path

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf-8 -*-
import os
import sys
import imp

from django.template.loader import BaseLoader
from django.template.loaders.filesystem import Loader as FileSystemLoader
from django.template.base import TemplateDoesNotExist

from django.conf import settings
from django.db.models.loading import get_app

class Loader(FileSystemLoader):
    '''
    Loading templates by path

    app.template_name -> app/templates/template_name.html
    app.subdir.template_name -> app/templates/subdir/template_name.html

    '''
    def get_template_sources(self, template_name, template_dirs=None):
        app_name, template_name = template_name.split('.',1)

        if not template_dirs:
            template_dirs = []
        try:
            template_dir = os.path.join(os.path.dirname(get_app(app_name).__file__), 'templates')
        except Exception:
            raise TemplateDoesNotExist
        template_dirs.append(template_dir)
        template_name = '%s.html'%template_name.replace('.','/')
        return super(Loader, self).get_template_sources(template_name, template_dirs)

More like this

  1. Create variables within templates by nkwenti 5 years, 10 months ago
  2. Variable inspect filter by buriy 5 years, 11 months ago
  3. Single Django App behind multiple Apache Proxies by chadmaine 6 years, 11 months ago
  4. favicon Template Tag by benjy_mouse 4 years, 2 months ago
  5. filter for extracting a number of paragraphs from any HTML code by rafadev 2 years, 10 months ago

Comments

(Forgotten your password?)