Login

Template class to test custom tag libraries

Author:
a.v.khodyrev
Posted:
July 18, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

TestableTemplate behaves just like django.template.Template, but you can give it a list of template.Libraries to load before parsing the template. This is equivalent to adding a bunch of {% load %} tags to the beginning of your template string, but you can use custom tag libraries which do not belong to Django applications' templatetags packages.

This is occasionally useful in testing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.template import Template, TemplateEncodingError,
StringOrigin, Lexer, Parser
from django.utils.encoding import smart_unicode

class TestableTemplate(Template):
    def __init__(self, template_string, origin=None,
            name='<Unknown Template>', libraries=[]):
        try:
            template_string = smart_unicode(template_string)
        except UnicodeDecodeError:
            raise TemplateEncodingError("Templates can only be
constructed from unicode or UTF-8 strings.")
        origin = StringOrigin(template_string)
        self.nodelist = my_compile_string(template_string, origin,
libraries)
        self.name = name

def my_compile_string(template_string, origin, libraries=[]):
    "Compiles template_string into NodeList ready for rendering"
    lexer = Lexer(template_string, origin)
    parser = Parser(lexer.tokenize())
    for lib in libraries:
        parser.add_library(lib)
    return parser.parse() 

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.