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  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PYTHON

Templating with Cheetah
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 20
    2005-12-27


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

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    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
     

       

    PYTHON ARTICLES

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek