best Template module

Quinn Dunkan quinn at pfennig.ugcs.caltech.edu
Fri Jan 14 12:40:10 EST 2000


On Fri, 14 Jan 2000 11:30:39 +0100, Alex Martelli <Alex.Martelli at think3.com>
wrote:
>Otis Gospodnetic writes:
>
>> Could anyone recommend a good 'Template module'?
>> 
>> Template module - a module that will let me create a plan text/HTML
>> file with some special markup/tags that I can then replace by some text
>> values from within my Python code
>> 
>> good - fast execution and not too complex :)
>> 
>> 
>Shorn of the 'statement-level' functionality (conditionals and loops),
>this is what my smartcopy.py boils down to:

Also, if you want simple and fast, python's built-in interpolation tags work
just fine:

% cat >template
Dear %(sucker)s,
    We're glad you've signed up for the "10,000 DISPOSABLE PLASTIC GIZMOS"
program.  Your first shipment will arrive by %(date)s, following shipments
will arrive every %(interval)d days.
    Sincerely,
    %(shark)s
^D
% python
Python 1.5.2 (#7, Dec 16 1999, 12:11:26)  [GCC 2.7.2.3] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> s = open('template').read()
>>> print s %{'sucker': 'John Smith', 'date': 'tommorrow', 'interval': 7,
...         'shark': 'Mr. Black'}
Dear John Smith,
    We're glad you've signed up for the "10,000 DISPOSABLE PLASTIC GIZMOS"
program.  Your first shipment will arrive by tommorrow, following shipments
will arrive every 7 days.
    Sincerely,
    Mr. Black
>>>

s % locals() is also a popular idiom.

If you want to get more elaborate, check out the DocumentTemplate module from
the zope distribution.  You don't have to use it with zope, and you don't have
to generate html with it, although it assumes you are.  The other thing which
may or may not be an advantage is that DT restricts embedded python statements
to 'safe' ones.



More information about the Python-list mailing list