Login

Loading templates by app path

Author:
apkawa
Posted:
June 29, 2011
Language:
Python
Version:
1.2
Tags:
template loader
Score:
1 (after 1 ratings)
Loading templates by path

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

Usage: append in settings.TEMPLATE_LOADERS and using render_to('app.index', context)

 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 7 years, 2 months ago
  2. Single Django App behind multiple Apache Proxies by chadmaine 8 years, 4 months ago
  3. Variable inspect filter by buriy 7 years, 3 months ago
  4. favicon Template Tag by benjy_mouse 5 years, 6 months ago
  5. filter for extracting a number of paragraphs from any HTML code by rafadev 4 years, 2 months ago

Comments

Please login first before commenting.