"""A lightweight python templating engine in 70 lines of code. Each template is a subclass of Template. Templates should define a class attribute 'template' that contains the template code. Use a template by instantiating the class with a dictionary or keyword arguments. Get the expansion by converting the instance to a string. For example: class MyTemplate(templet.Template): template = "the $animal jumped over the $object." print MyTemplate(animal='cow', object='moon') The template language understands the following forms: $myvar - inserts the value of the variable 'myvar' ${...} - evaluates the expression and inserts the result ${{...}} - executes enclosed code; use 'self.write(text)' to insert text $$ - an escape for a single $ $ (at the end of the line) - a line continuation $ - shorthand for '${{self.sub_template(vars())}}' Of course in addition to the main template a Template class may have methods, members, subclasses, etc. Any class attribute ending with '_template' will be compiled into a subtemplate that can be called as a method or by using $<...>. This is helpful for decomposing a template and when subclassing. A longer example: import cgi class RecipeTemplate(templet.Template): template = r''' $dish $ $ ''' header_template = r'''

${cgi.escape(dish)}

''' body_template = r'''
    ${{ for item in ingredients: self.write('
  1. ', item, '\n') }}
''' This template can be expanded as follows: print RecipeTemplate(dish='burger', ingredients=['bun', 'beef', 'lettuce']) And it can be subclassed like this: class RecipeWithPriceTemplate(RecipeTemplate): header_template = "

${cgi.escape(dish)} - $$$price

\n" Templet is by David Bau and was inspired by Tomer Filiba's Templite class. For details, see http://davidbau.com/templet Templet is posted by David Bau under BSD-license terms. Copyright (c) 2007, David Bau All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Templet nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys, re class _TemplateMetaClass(type): __pattern = re.compile(r"""\$( # Directives begin with a $ \$ | # $$ is an escape for $ [^\S\n]*\n | # $\n is a line continuation [_a-z][_a-z0-9]* | # $simple Python identifier \{(?!\{)[^\}]*\} | # ${...} expression to eval \{\{.*?\}\} | # ${{...}} multiline code to exec <[_a-z][_a-z0-9]*> | # $ method call )(?:(?:(?<=\}\})|(?<=>))[^\S\n]*\n)? # eat some trailing newlines """, re.IGNORECASE | re.VERBOSE | re.DOTALL) def __realign(cls, str): """Removes any leading empty columns of spaces and an initial empty line""" lines = str.splitlines(); if lines and not lines[0].strip(): del lines[0] lspace = [len(l) - len(l.lstrip()) for l in lines if l.lstrip()] margin = len(lspace) and min(lspace) return '\n'.join(l[margin:] for l in lines) def __filename(cls, n, globals): """Returns 'filename.py ' for labeling python errors""" if '__file__' in globals: return '%s: <%s %s>' % (globals['__file__'], cls.__name__, n) return '<%s %s>' % (cls.__name__, n) def __compile(cls, template, name): globals = sys.modules[cls.__module__].__dict__ code = [] for i, part in enumerate(cls.__pattern.split(cls.__realign(template))): if i % 2 == 0: if part: code.append('self.write(%s)' % repr(part)) else: if part == '$': code.append('self.write("$")') elif part.endswith('\n'): continue elif part.startswith('{{'): code.append(cls.__realign(part[2:-2])) elif part.startswith('{'): code.append('self.write(%s)' % part[1:-1]) elif part.startswith('<'): code.append('self.%s(vars())' % part[1:-1]) elif part == '': raise SyntaxError('Unescaped $ in ' + cls.__filename(name, globals)) else: code.append('self.write(%s)' % part) code = compile('\n'.join(code), cls.__filename(name, globals), 'exec') del cls, template, name, i, part def expand(self, _dict = None, **kw): if _dict: kw.update([i for i in _dict.iteritems() if i[0] not in kw]) kw['self'] = self exec code in globals, kw return expand def __init__(cls, *args): for attr, val in cls.__dict__.items(): if attr == 'template' or attr.endswith('_template'): if isinstance(val, basestring): setattr(cls, attr, cls.__compile(val, attr)) type.__init__(cls, *args) class Template(object): """A base class for string template classes.""" __metaclass__ = _TemplateMetaClass def __init__(self, *args, **kw): self.output = [] self.template(*args, **kw) def write(self, *args): self.output.extend([str(a) for a in args]) def __str__(self): return ''.join(self.output) class UnicodeTemplate(object): """A base class for unicode template classes.""" __metaclass__ = _TemplateMetaClass def __init__(self, *args, **kw): self.output = [] self.template(*args, **kw) def write(self, *args): self.output.extend([unicode(a) for a in args]) def __unicode__(self): return u''.join(self.output) def __str__(self): return unicode(self).encode('utf-8') # When executed as a script, run some testing code. if __name__ == '__main__': ok = True def expect(actual, expected): global ok if expected != actual: print "error - got:\n%s" % repr(actual) ok = False class TestAll(Template): """A test of all the $ forms""" template = r""" Bought: $count ${name}s$ at $$$price. ${{ for i in xrange(count): self.write(TestCalls(vars()), "\n") # inherit all the local $vars }} Total: $$${"%.2f" % (count * price)} """ class TestCalls(Template): """A recursive test""" template = "$name$i ${*[TestCalls(name=name[0], i=n) for n in xrange(i)]}" expect( str(TestAll(count=5, name="template call", price=1.23)), "Bought: 5 template calls at $1.23.\n" "template call0 \n" "template call1 t0 \n" "template call2 t0 t1 t0 \n" "template call3 t0 t1 t0 t2 t0 t1 t0 \n" "template call4 t0 t1 t0 t2 t0 t1 t0 t3 t0 t1 t0 t2 t0 t1 t0 \n" "Total: $6.15\n") class TestBase(Template): template = r""" $ $ """ class TestDerived(TestBase): head_template = "$name" body_template = "${TestAll(vars())}" expect( str(TestDerived(count=4, name="template call", price=2.88)), "template call\n" "" "Bought: 4 template calls at $2.88.\n" "template call0 \n" "template call1 t0 \n" "template call2 t0 t1 t0 \n" "template call3 t0 t1 t0 t2 t0 t1 t0 \n" "Total: $11.52\n" "\n") class TestUnicode(UnicodeTemplate): template = u""" \N{Greek Small Letter Pi} = $pi """ expect( unicode(TestUnicode(pi = 3.14)), u"\N{Greek Small Letter Pi} = 3.14\n") goterror = False try: class TestError(Template): template = 'Cost of an error: $0' except SyntaxError: goterror = True if not goterror: print 'TestError failed' ok = False if ok: print "OK"