The problem: {% extends "./../base.html" %} won't work with extends.
It causes a lot of inconvenience, if you have an extensive hierarchy of django templates. This library allows relative paths in argument of 'extends' and 'include' template tags. Relative path must start from "./"
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.
{% load relative_path %}
{% include "./base.html" %}
include base.html, located near of your template.
Warning! The rule 'extends tag must be first tag into template' is disabled by this library. Write your template with caution.
Compatibility Code was tested with Django versions from 1.4 to 1.9
Installation.
Installation is differs for Django version 1.9 and previous versions, because 1.9 brings many changes into template's mechanizm.
Django 1.9
Plug reference to library code in 'TEMPLATES' key of settings.py or django.settings.configure()
``` TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(ROOT_PROJECT, 'tpl').replace('\', '/')], 'OPTIONS': {
'loaders': [
'dotted_path_to_relative_path_file.FileSystem19',
'dotted_path_to_relative_path_file.AppDirectories19',
],
'libraries': {
'relative_path': 'dotted_path_to_relative_path_file',
},
},
}]
```
Django 1.4/1.8
Put 'relative_path.py' file to the 'templatetags' folders of your app. (app must be included into INSTALLED_APPS tuple)
In settings.py or django.settings.configure(), replace standard django template loaders by loaders from this library
TEMPLATE_LOADERS = (
'dotted_path_to_relative_path_file.FileSystem',
'dotted_path_to_relative_path_file.AppDirectories',
)
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | """
Library for enable relative pathes in django template tags
'extends' and 'include'
(C) 2016 by Vitaly Bogomolov [email protected]
Origin: https://github.com/vb64/django.templates.relative.path
"""
import posixpath
from django import template
from django.conf import settings
from django.template.base import Template as TemplateParent
from django.template.base import (Lexer, Parser, StringOrigin,
TemplateEncodingError, TemplateSyntaxError,
token_kwargs)
from django.template.loader_tags import ExtendsNode as ExtendsNodeParent
from django.template.loader_tags import IncludeNode
from django.template.loaders import app_directories as ad
from django.template.loaders import filesystem as fs
from django.utils.encoding import smart_unicode
# django 1.9
try:
from django.template import (
TemplateDoesNotExist,
Template as Template19parent,
)
from django.utils.inspect import func_supports_parameter
from django.template.base import DebugLexer as DebugLexer19
from django.template.utils import get_app_template_dirs
except:
pass
################################################
# template loaders
################################################
def compile_string(template_string, origin, name):
"""
Set template name to Parser instance
"""
if settings.TEMPLATE_DEBUG:
from django.template.debug import DebugLexer, DebugParser
lexer_class, parser_class = DebugLexer, DebugParser
else:
lexer_class, parser_class = Lexer, Parser
lexer = lexer_class(template_string, origin)
parser = parser_class(lexer.tokenize())
parser.template_name = name
return parser.parse()
class Template(TemplateParent):
"""
Pass template name to Parser
"""
def __init__(self, template_string, origin=None, name=None, engine=None):
try:
template_string = smart_unicode(template_string)
except UnicodeDecodeError:
raise TemplateEncodingError("Templates can only be constructed "
"from unicode or UTF-8 strings.")
if settings.TEMPLATE_DEBUG and origin is None:
origin = StringOrigin(template_string)
self.nodelist = compile_string(template_string, origin, name)
self.name = name
self.origin = origin
# !!! ATTENTION !!!
# always use default engine for render
try:
from django.template.engine import Engine
self.engine = Engine.get_default()
except Exception:
self.engine = None
class FileSystem(fs.Loader):
"""
Use modified Template class
"""
is_usable = True
def load_template(self, template_name, template_dirs=None):
"""
Use modified Template class and pass template name
"""
source, origin = self.load_template_source(
template_name,
template_dirs
)
template = Template(
source,
name=template_name
)
return template, origin
class AppDirectories(ad.Loader):
"""
Use modified Template class
"""
is_usable = True
def load_template(self, template_name, template_dirs=None):
"""
Use modified Template class and pass template name
"""
source, origin = self.load_template_source(
template_name, template_dirs
)
template = Template(source, name=template_name)
return template, origin
class Template19(Template19parent):
"""
Pass template name to Parser into Django 1.9
"""
def compile_nodelist(self):
"""
Pass template name to parser instance
"""
if self.engine.debug:
lexer = DebugLexer19(self.source)
else:
lexer = Lexer(self.source)
tokens = lexer.tokenize()
parser = Parser(
tokens,
self.engine.template_libraries,
self.engine.template_builtins,
)
parser.template_name = self.origin.template_name
try:
return parser.parse()
except Exception as e:
if self.engine.debug:
e.template_debug = self.get_exception_info(e, e.token)
raise
class FileSystem19(fs.Loader):
"""
Use modified Template19 class
"""
def get_template(self, template_name, template_dirs=None, skip=None):
"""
Use modified Template19 class and
pass template name to instance
"""
tried = []
args = [template_name]
if func_supports_parameter(self.get_template_sources, 'template_dirs'):
args.append(template_dirs)
for origin in self.get_template_sources(*args):
if skip is not None and origin in skip:
tried.append((origin, 'Skipped'))
continue
try:
contents = self.get_contents(origin)
except TemplateDoesNotExist:
tried.append((origin, 'Source does not exist'))
continue
else:
return Template19(
contents, origin, origin.template_name, self.engine,
)
raise TemplateDoesNotExist(template_name, tried=tried)
class AppDirectories19(FileSystem19):
"""
Use modified Template19 class
"""
def get_dirs(self):
"""
Same as core function
"""
return get_app_template_dirs('templates')
################################################
# template tags 'extends' and 'include'
################################################
register = template.Library()
class ExtendsNode(ExtendsNodeParent):
"""
!!! ATTENTION !!!
it disable rule, that 'extends' must be first tag in template
this need for first {% load relative_path %} tag
"""
must_be_first = False
def construct_relative_path(name, relative_name):
"""
Construct new path from saved into parser instance name and given
relative path in extends/include handlers with posixpath functions,
then handle new path by standard extends/include rules.
"""
if not relative_name.startswith('"./'):
# argument is variable or literal, that not contain relative path
return relative_name
new_name = posixpath.normpath(
posixpath.join(
posixpath.dirname(name.lstrip('/')),
relative_name.strip('"')
)
)
if new_name.startswith('../'):
raise TemplateSyntaxError(
"Relative name '%s' have more parent folders, then given template name '%s'"
% (relative_name, name)
)
if name.lstrip('/') == new_name:
raise TemplateSyntaxError(
"Circular dependencies: relative path '%s' was translated to template name '%s'"
% (relative_name, name)
)
return '"%s"' % new_name
@register.tag('extends')
def do_extends(parser, token):
"""
Same as core function, with construct_relative_path call
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument" % bits[0])
bits[1] = construct_relative_path(parser.template_name, bits[1])
parent_name = parser.compile_filter(bits[1])
nodelist = parser.parse()
if nodelist.get_nodes_by_type(ExtendsNode):
raise TemplateSyntaxError(
"'%s' cannot appear more than once in the same template"
% bits[0]
)
return ExtendsNode(nodelist, parent_name)
@register.tag('include')
def do_include(parser, token):
"""
Same as core function, with construct_relative_path call
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError(
"%r tag takes at least one argument: "
"the name of the template to be included."
% bits[0]
)
options = {}
remaining_bits = bits[2:]
while remaining_bits:
option = remaining_bits.pop(0)
if option in options:
raise TemplateSyntaxError('The %r option was specified more '
'than once.' % option)
if option == 'with':
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if not value:
raise TemplateSyntaxError('"with" in %r tag needs at least '
'one keyword argument.' % bits[0])
elif option == 'only':
value = True
else:
raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
(bits[0], option))
options[option] = value
isolated_context = options.get('only', False)
namemap = options.get('with', {})
bits[1] = construct_relative_path(parser.template_name, bits[1])
return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap,
isolated_context=isolated_context)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.