Welcome, guest | Sign In | My Account | Store | Cart

Revised version of Templite, a light-weight, fully functional, general purpose templating engine

Python, 228 lines
  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
#!/usr/bin/env python
#
#       Templite+
#       A light-weight, fully functional, general purpose templating engine
#
#       Copyright (c) 2009 joonis new media
#       Author: Thimo Kraemer <thimo.kraemer@joonis.de>
#
#       Based on Templite - Tomer Filiba
#       http://code.activestate.com/recipes/496702/
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#

import sys, re

class Templite(object):
    auto_emit = re.compile('(^[\'\"])|(^[a-zA-Z0-9_\[\]\'\"]+$)')
    
    def __init__(self, template, start='${', end='}$'):
        if len(start) != 2 or len(end) != 2:
            raise ValueError('each delimiter must be two characters long')
        delimiter = re.compile('%s(.*?)%s' % (re.escape(start), re.escape(end)), re.DOTALL)
        offset = 0
        tokens = []
        for i, part in enumerate(delimiter.split(template)):
            part = part.replace('\\'.join(list(start)), start)
            part = part.replace('\\'.join(list(end)), end)
            if i % 2 == 0:
                if not part: continue
                part = part.replace('\\', '\\\\').replace('"', '\\"')
                part = '\t' * offset + 'emit("""%s""")' % part
            else:
                part = part.rstrip()
                if not part: continue
                if part.lstrip().startswith(':'):
                    if not offset:
                        raise SyntaxError('no block statement to terminate: ${%s}$' % part)
                    offset -= 1
                    part = part.lstrip()[1:]
                    if not part.endswith(':'): continue
                elif self.auto_emit.match(part.lstrip()):
                    part = 'emit(%s)' % part.lstrip()
                lines = part.splitlines()
                margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip())
                part = '\n'.join('\t' * offset + l[margin:] for l in lines)
                if part.endswith(':'):
                    offset += 1
            tokens.append(part)
        if offset:
            raise SyntaxError('%i block statement(s) not terminated' % offset)
        self.__code = compile('\n'.join(tokens), '<templite %r>' % template[:20], 'exec')

    def render(self, __namespace=None, **kw):
        """
        renders the template according to the given namespace. 
        __namespace - a dictionary serving as a namespace for evaluation
        **kw - keyword arguments which are added to the namespace
        """
        namespace = {}
        if __namespace: namespace.update(__namespace)
        if kw: namespace.update(kw)
        namespace['emit'] = self.write
        
        __stdout = sys.stdout
        sys.stdout = self
        self.__output = []
        eval(self.__code, namespace)
        sys.stdout = __stdout
        return ''.join(self.__output)
    
    def write(self, *args):
        for a in args:
            self.__output.append(str(a))


if __name__ == '__main__':
    
    template = r"""
This we already know:
<html>
    <body>
        ${
        def say_hello(arg):
            emit("hello ", arg, "<br>")
        }$

        <table>
            ${
                for i in range(10):
                    emit("<tr><td> ")
                    say_hello(i)
                    emit(" </tr></td>\n")
            }$
        </table>

        ${emit("hi")}$

        tralala ${if x > 7:
            say_hello("big x")}$ lala

        $\{this is escaped starting delimiter

        ${emit("this }\$ is an escaped ending delimiter")}$

        ${# this is a python comment }$

    </body>
</html>

But this is completely new:
${if x > 7:}$
    x is ${emit('greater')}$ than ${print x-1}$ Well, the print statement produces a newline.
${:else:}$
 This terminates the previous code block and starts an else code block
 Also this would work: $\{:end}\$$\{else:}\$, but not this: $\{:end}\$ $\{else:}\$
${:this terminates the else-block
only the starting colon is essential}$

So far you had to write:
${
    if x > 3:
        emit('''
            After a condition you could not continue your template.
            You had to write pure python code.
            The only way was to use %%-based substitutions %s
            ''' % x)
}$

${if x > 6:}$
    Now you do not need to break your template ${print x}$
${:elif x > 3:}$
    This is great
${:endif}$

${for i in range(x-1):}$  Of course you can use any type of block statement ${i}$ ${"fmt: %s" % (i*2)}$
${:else:}$
Single variables and expressions starting with quotes are substituted automatically.
Instead $\{emit(x)}\$ you can write $\{x}\$ or $\{'%s' % x}\$ or $\{"", x}\$
Therefore standalone statements like break, continue or pass
must be enlosed by a semicolon: $\{continue;}\$
The end
${:end-for}$
"""

    t = Templite(template)
    print t.render(x=8)


    # Output is:
    """
This we already know:
<html>
    <body>
        

        <table>
            <tr><td> hello 0<br> </tr></td>
<tr><td> hello 1<br> </tr></td>
<tr><td> hello 2<br> </tr></td>
<tr><td> hello 3<br> </tr></td>
<tr><td> hello 4<br> </tr></td>
<tr><td> hello 5<br> </tr></td>
<tr><td> hello 6<br> </tr></td>
<tr><td> hello 7<br> </tr></td>
<tr><td> hello 8<br> </tr></td>
<tr><td> hello 9<br> </tr></td>

        </table>

        hi

        tralala hello big x<br> lala

        ${this is escaped starting delimiter

        this }$ is an escaped ending delimiter

        

    </body>
</html>

But this is completely new:

    x is greater than 7
 Well, the print statement produces a newline.


So far you had to write:

        After a condition you could not continue your template.
        You had to write pure python code.
        The only way was to use %-based substitutions 8
        


    Now you do not need to break your template 8



  Of course you can use any type of block statement 0 fmt: 0
  Of course you can use any type of block statement 1 fmt: 2
  Of course you can use any type of block statement 2 fmt: 4
  Of course you can use any type of block statement 3 fmt: 6
  Of course you can use any type of block statement 4 fmt: 8
  Of course you can use any type of block statement 5 fmt: 10
  Of course you can use any type of block statement 6 fmt: 12

Single variables and expressions starting with quotes are substituted automatically.
Instead ${emit(x)}$ you can write ${x}$ or ${'%s' % x}$ or ${"", x}$
Therefore standalone statements like break, continue or pass
must be enlosed by a semicolon: ${continue;}$
The end
"""

Similar to Templite, except that you do not need to break your template within block statements. Single variables and expressions starting with quotes are substituted automatically. Starting and ending delimiters are variable.

4 comments

Alain Mellan 14 years, 12 months ago  # | flag

I replaced lines 58 and 59 with:

margin = min(map(lambda l: len(l) - len(l.lstrip()), filter(lambda l: l.strip(), lines)))
part = '\n'.join(map(lambda l: '\t' * offset + l[margin:], lines))

To make it work with older revisions of Python (2.3.4)

It's an awesome script, saved me a lot of typing :-)

Don Welch 13 years, 10 months ago  # | flag

auto_emit is declared as a class variable, so shouldn't line 55:

elif self.auto_emit.match(part.lstrip()):

be this instead?:

elif Templite.auto_emit.match(part.lstrip()):

Interestingly, the test code runs OK either way.

a 13 years, 9 months ago  # | flag

Really nice script!

I' added this to main, just before the test code starts:

if '--demo' not in sys.argv:
    vars = eval('dict(' + ' '.join(sys.argv[1:]) + ')')
    sys.stdout.write(Templite(sys.stdin.read()).render(vars))
    sys.exit(0)

This way I can easily use templite as a command line tool :)

$ echo 'xx ${v}$ yy ${t}$ zz' | python templite.py v=[1,2,3,4], t=5 xx [1, 2, 3, 4] yy 5 zz

-- Luca (http://www.llucax.com.ar/), using a Bugmenot account =)

Thimo Kraemer (author) 13 years, 3 months ago  # | flag

New versions of this script are hosted at http://www.joonis.de/wiki/TemplitePythonTemplatingEngine

Created by Thimo Kraemer on Mon, 23 Feb 2009 (MIT)
Python recipes (4591)
Thimo Kraemer's recipes (3)

Required Modules

Other Information and Tasks