Python
  Home arrow Python arrow Page 3 - Templating with Cheetah
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Templating with Cheetah
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 15
    2005-12-27

    Table of Contents:
  • Templating with Cheetah
  • Basic Templating
  • Compiling Templates
  • More Logic

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Templating with Cheetah - Compiling Templates


    (Page 3 of 4 )

    Compiling a template converts it into Python code, which eliminates the need for Cheetah to go through a template and replace everything. This means that Cheetah can work faster. Compiling a template is very simple, and all it involves is a call to Cheetah. Take a look at this template, quote.tmpl, which provides a placeholder for a random quotation:

    <center>
    <i>$quotation</i><br />
    -- $speaker
    </center>

    To compile this, we pass a few arguments to cheetah:

    cheetah compile quote.tmpl

    Cheetah then generates the file quote.py, which contains the class quote. The class can be imported into a Python script and then used similarly to the Template class:

    import random
    from quote import quote

    # Define a list of quotations
    quotations = [ [ 'It is easier to find people fit to govern
    themselves than people fit to govern others.', 'Lord Acton' ],\
                   [ 'A house divided against itself cannot stand.',
    'Abraham Lincoln' ],\
                   [ 'Before anything else, preparation is the key to
    success.', 'Alexander Graham Bell' ] ]

    # Pick a random quotation
    quotation = random.choice ( quotations )

    # Print the product
    print quotation ( searchList = [{ 'quotation': quotation [0],
    'author': quotation [1] }]

    Adding Logic

    Instead of having a Python script control all the logic for a certain template, it's possible to slip a bit of simple logic into a template. Cheetah makes this possible through special directives. For example, say that you want to display a certain message if one condition is met and a certain message if another condition is met. The #if directive can be used for this task, rather than doing work in Python. Take a look at greeting.tmpl, which displays different greetings for different times of day:

    #if $hour < 12
    Good morning!
    #else if $hour >= 12 and $hour <=18
    Good afternoon!
    #else
    Good evening!
    #end if

    All we need to do is pass the hour of the day to the script, and it will display the appropriate message:

    import time
    from Cheetah.Template import Template

    hour = time.localtime() [3]
    print Template ( file = 'greeting.tmpl', searchList = [{ 'hour':
    hour }] )

    The #unless directive is similar to the #if directive, but it returns the opposite of what the expression returns. If the expression is true, then the contained code is not executed. If the expression is false, then the contained code executes. Take this template for example:

    #unless $a
    < Message >
    #end unless

    Unless $a returns a true value, “< Message >” is displayed to the user. If $a does return a true value, then the message is never displayed.

    Cheetah also allows for loops to be used within templates. The #for directive acts as a for loop, as in listPresidents.tmpl:

    Presidents:
    #for $name in $names:
    <br />$name
    #end for

    To see the template in action, we need to pass a list to take the place of the $names variable:

    from Cheetah.Template import Template

    presidents = [ 'George Washington', 'John Adams', 'Thomas
    Jefferson', 'James Madison', 'James Monroe' ]

    print Template ( file = 'listPresidents.tmpl', searchList =
    [{ 'names': presidents }] )

    The #repeat directive simply repeats something a specified amount of times. For example, say I wanted to make a primitive horizontal bar graph using “|” characters. I could use the #repeat directive to do this in graph.tmpl:

    #repeat $x
    |
    #end repeat

    We can now substitute $x for the length of the graph:

    from Cheetah.Template import Template

    # Set the length of the bar graph
    x = 10

    print Template ( file = 'graph.tmpl', searchList = [{ 'x': x }] )

    If you run the above script, however, you will see that each “|” character is put on a new line. This can be fixed using the #slurp directive:

    #repeat $x
    |#slurp
    #end repeat

    Lastly, the #while directive acts as a while loop:

    #set $x = 1
    #while $x <= 10
    $x
    #set $x = $x + 1
    #end while

    Notice that the above template uses the #set directive. This simply sets the value of a variable.

    Cheetah also contains #break and #continue directives for use in loops. This template will not display “4” or anything past “5”:

    #set $x = 1
    #while $x <= 10
    #if $x == 4
    #continue
    #end if
    $x
    #if $x ==5
    #break
    #set $x = $x + 1
    #end if
    #end while

    More Python Articles
    More By Peyton McCullough


       · Hey, all,I know that a lot of people have heard of Cheetah, but I'm not sure all...
       · I believe it should be 'python setup.py install'.
       · file ( 'count.txt', 'r' ).write ( str ( count ) )should be file ( 'count.txt',...
       · [b]print quotation ( searchList = [{ 'quotation': quotation [0],'author':...
       · This article was nice to show the simplcity of Cheetah, but falls far short of being...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway