"""
Custom template loader, enables Cheetah-like comments, saves the pain
of {%comment%} .. {%endcomment%}
This is a template loader, see http://www.djangoproject.com/documentation/templates_python/#loading-templates
Suppose you saved this in :
myproject/utils/loaders.py
In settings.py, you should enable it, by adding it at the top of TEMPLATE_LOADERS, like :
TEMPLATE_LOADERS = (
'myproject.utils.loaders.load_template_source',
'django.template.loaders.filesystem.load_template_source',
...
"""
import os
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.template.loaders.filesystem import get_template_sources
#################################
def _handle_cheetah_comments(filepath):
"""
Returns a string with cheetah-style comments stripped.
This takes care of :
1) ## blah blah
2) #*
blah blah
*#
3) display this ## not this
Please note that the whole lines starting with #* or *# are removed.
This code doesn't handle :
1) *# display this
"""
output = []
multiline_comment = False
for line in open(filepath):
sline = line.strip()
if sline.startswith("##"):
continue
elif sline.startswith("#*"):
multiline_comment = True
continue
elif sline.startswith("*#"):
multiline_comment = False
continue
else:
if multiline_comment:
continue
else:
output.append(line.split("##")[0])
# Multiline comments should be closed at the end of the template
if multiline_comment:
raise Exception, "Multiline comment (#* .. *# syntax) not closed in %s" % filepath
return "\n".join(output)
############################################################
def load_template_source(template_name, template_dirs=None):
"""
Enables Cheetah-style comments.
Almost like http://code.djangoproject.com/browser/django/trunk/django/template/loaders/filesystem.py
"""
tried = []
for filepath in get_template_sources(template_name, template_dirs):
try:
# return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
input = _handle_cheetah_comments(filepath).decode(settings.FILE_CHARSET)
return (input, filepath)
except IOError:
tried.append(filepath)
if tried:
error_msg = "Tried %s" % tried
else:
error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
raise TemplateDoesNotExist, error_msg
load_template_source.is_usable = True
Comments
Good idea! Thanks, Oliver!
#