The Artima Developer Community
Sponsored Link

Python Buzz Forum
Ludicrously simple templates with Python

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Simon Willison

Posts: 282
Nickname: simonw
Registered: Jun, 2003

Simon Willison is a web technology enthusiast studying for a Computer Science degree at Bath Uni, UK
Ludicrously simple templates with Python Posted: Jul 28, 2003 4:30 PM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Simon Willison.
Original Post: Ludicrously simple templates with Python
Feed Title: Simon Willison: Python
Feed URL: http://simon.incutio.com/syndicate/python/rss1.0
Feed Description: Simon Willison's Python cateory
Latest Python Buzz Posts
Latest Python Buzz Posts by Simon Willison
Latest Posts From Simon Willison: Python

Advertisement

A long, long time ago I wrote my first ever PHP templating system. It was pretty simple; it consisted of a function that took two arguments: the name of a template file, and an associative array of replacements to make on that file.

I've finally got around to playing with Python CGIs for web development recently, and decided I needed a similar system. Thanks to Python's powerful string formatting operator, it ended up as a one-liner:

def template(file, vars):
    return open(templatedir.template, 'r').read() % vars

Presuming you've set templatedir at the top of the script, the above function lets you load a template and make some simple replacements on it with a single function call. For example:

<h3>%(title)s</h3>

%(body)s

<p class="footer">Posted: %(date)s</p>

With the above saved in the template directory as "entry.tpl", the template function above can be used thus:


print template('entry.tpl', {
    'title':'A blog entry', 
    'body':'Entry goes here...',
    'date':'3rd July 2003'})

The work is all done by the % vars bit at the end of the line. Since vars is a dictionary, Python substitutes the named items in the dictionary for their corresponding %(varname)s tokens in the string loaded from the template file. More information on string formatting operations can be found in the manual.

As templating systems go, it's far from the most useful or complete solution. It does however show that a little Python can go quite a long way.

Read: Ludicrously simple templates with Python

Topic: Day 3: Civilization Previous Topic   Next Topic Topic: JSP Comments

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use