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

It is not so easy to put template engine and the template itself together, and to separate logic and a template. This example should define the value substituted for the slot of the easy source code for using template engine, the function of template engine, a template, and a template, and they should operate well by calling using render function.

Below is an e-mail generate and sendings.

Python, 50 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
def render(template, script, **kargs):  

    funcname = 'execute_render'
    varlist = []
    for key in kargs.keys():
        varlist.append("%s = globals()['%s']" % (key, key))
    kargs['__template__'] = template

    # Generate a function so run with template code.
    funccode = compile(
        'def %s():\n' % funcname
        # Assign to local variables.
        + '%s\n' % '\n'.join(map(lambda s: ' %s' % s, varlist))
        # One level indent
        + '%s\n' % '\n'.join(map(lambda s: ' %s' % s, script.split('\n'))),
        funcname, 'exec')
    # Generate a function and execution.
    eval(funccode, kargs, locals())
    return eval('%s()' % funcname)

def test():
    src = '''
import tinpy
return tinpy.build(__template__, vals=header_dict)
'''
    tpl = """\
Date: [% var vals['datetime'] %]
From: [% var vals['fromaddr'] %]
To: [% var vals['toaddr'] %]    
Subject: Test mail

This is a test mail.
"""

    import time
    import smtplib
    
    header_dict = {
        'datetime': time.strftime('%a, %d %b %Y %T %z'),
        'fromaddr': 'from@example.com',
        'toaddr': 'to@example.com'}

    maildata = render(tpl, src, header_dict=header_dict)
    server = smtplib.SMTP('localhost')
    server.sendmail(
        header_dict['fromaddr'], [header_dict['toaddr']],
        maildata.replace('\n', '\r\n'))
    server.quit()

test()

It example uses template rendering module is tinpy. See also http://sourceforge.net/projects/tinpy

A name "__template__" is template character string to use script. Below is a example of generating a SHA hex-digest:

src = ''' import sha return __template__ % sha.new(base).hexdigest() '''

It returns 'foobar -> 8843d7f92416211de9ebb963ff4ce28125932878'

print render('foobar -> %s', src, base='foobar')