"""A lightweight python templating engine in 75 lines of code. Each template is a subclass of Template. Templates should define a 'template' method that contains the template string. Use a template by instantiating the class with the template arguments. Get the expansion by converting the instance to a string. For example: class Poem(templet.Template): def template(self, animal, thing): "the $animal jumped over the $thing." print Poem('cow', 'moon') The template language understands the following forms: $myvar - inserts the value of the variable 'myvar' ${...} - evaluates the expression and inserts the result ${{...}} - executes code; use 'self.write(text)' to insert text $$ - an escape for a single $ $ (at the end of the line) - a line continuation Of course in addition to the main template method a Template class may have other methods, members, subclasses, etc. Any method having a name ending with '_template' will be compiled into a template method that can be called from the main template. This is helpful for decomposing a template and when subclassing. The base __init__ just passes all its *args and **kwargs to the template() method after initializing self.output to []. You can provide your own __init__ that does other things. A longer example: import cgi class RecipeTemplate(templet.Template): def __init__(self, dish, ingredients): self.dish = dish self.ingredients = ingredients self.output = [] self.template() def template(self): r''' ${self.dish} ${{self.header_template()}} ${{self.body_template()}} ''' def header_template(self): r'''

${cgi.escape(self.dish)}

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

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

\n" Templet is by David Bau and was inspired by Tomer Filba's Templite class. Templet is posted here 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, inspect 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, spaces = ''): 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 = lspace and min(lspace) or 0 return '\n'.join(spaces + l[margin:] for l in lines) def __filename(cls, n, globals): if '__file__' in globals: return '%s: <%s %s>' % (globals['__file__'], cls.__name__, n) return '<%s %s>' % (cls.__name__, n) def __compile(cls, func): argspec = inspect.getargspec(func) if not argspec[0] or argspec[3] and len(argspec[0]) == len(argspec[3]): raise TypeError('%s.%s takes no self argument' % (cls.__name__, func.__name__)) if len(func.func_code.co_code) > 4: raise TypeError('%s.%s contains code (template expected)' % (cls.__name__, func.__name__)) s = argspec[0][0] code = ['def %s%s:' % (func.__name__, inspect.formatargspec(*argspec))] for i, part in enumerate(cls.__pattern.split(cls.__realign(func.__doc__))): if i % 2 == 0: if part: code.append(' %s.write(%s)' % (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]) else: code.append(' self.write(%s)' % part) globals, locals = sys.modules[cls.__module__].__dict__, {} code = compile('\n'.join(code), cls.__filename(func.__name__, globals), 'exec') exec code in globals, locals return locals[func.__name__] def __init__(cls, *args): for attr, val in cls.__dict__.items(): if attr == 'template' or attr.endswith('_template'): if inspect.isfunction(val): setattr(cls, attr, cls.__compile(val)) type.__init__(cls, *args) class Template(object): """A base class for exec-style templates.""" __metaclass__ = _TemplateMetaClass def __init__(self, *args, **kw): self.output = [] self.template(*args, **kw) def write(self, *args): for a in args: if isinstance(a, Template): self.output.extend(a.output) else: self.output.append(str(a)) def __str__(self): return ''.join(self.output) # 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" % actual ok = False class TestAll(Template): """A test of all the $ forms""" def template(self, count, name, price=0.0): r""" Bought: $count ${name}s$ at $$$price. ${{ for i in xrange(count): self.write(TestCalls(name, i), "\n") }} Total: $$${"%.2f" % (count * price)} """ class TestCalls(Template): """A recursive test""" def template(self, name, i): "$name$i ${*[TestCalls(name[0], 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): def template(self, *args, **kw): r""" ${{self.head_template(*args, **kw)}} ${{self.body_template(*args, **kw)}} """ class TestDerived(TestBase): def head_template(self, name='name', **kw): "$name" def body_template(self, *args, **kw): "${TestAll(*args, **kw)}" 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") if ok: print "OK"