- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

11.2 Templating

The ‘string’ module includes a versatile Template class with a simplified syntax suitable for editing by end-users. This allows users to customize their applications without having to alter the application.

The format uses placeholder names formed by ‘$’ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing ‘$$’ creates a single escaped ‘$’:

    >>> from string import Template
    >>> t = Template('${village}folk send $$10 to $cause.')
    >>> t.substitute(village='Nottingham', cause='the ditch
     fund')
    'Nottinghamfolk send $10 to the ditch fund.'

The substitute method raises a KeyError when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user supplied data may be incomplete and the safe_substitute method may be more appropriate--it will leave placeholders unchanged if data is missing:

    >>> t = Template('Return the $item to $owner.')
    >>> d = dict(item='unladen swallow')
    >>> t.substitute(d)
    Traceback (most recent call last):
      . . .
    KeyError: 'owner'
    >>> t.safe_substitute(d)
    'Return the unladen swallow to $owner.'

Template subclasses can specify a custom delimiter. For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format:

    >>> import time, os.path
    >>> photofiles = ['K74.jpg', 'K76.jpg', 'K77.jpg']
    >>> class BatchRename(Template):
    ...     delimiter = '%'
    >>> fmt = raw_input('Rename as (%d-date %n-no %f-fmt): ')
    Rename as (%d-date %n-no %f-fmt): Pic_%n%f
    
    >>> t = BatchRename(fmt)
    >>> date = time.strftime('%d%b%y')
    >>> for i, filename in enumerate(photofiles):
    ...     base, ext = os.path.splitext(filename)
    ...     newname = t.substitute(d=date, n=i, f=ext)
    ...     print '%s --> %s' % (filename, newname)
    
    K74.jpg --> Pic_0.jpg
    K76.jpg --> Pic_1.jpg
    K77.jpg --> Pic_2.jpg

Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.

ISBN 0954161769An Introduction to PythonSee the print edition