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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.