### Install Cheetah Python Package Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Instructions for installing the Cheetah templating engine using Python's distutils. This covers both system-wide installation and installation to an alternate, user-specified location. Ensure Python is in your PATH for these commands to work correctly. ```Shell python setup.py install ``` ```Shell python setup.py install --home /home/tavis ``` ```Shell python setup.py install --install-lib /home/tavis/lib/python ``` -------------------------------- ### Basic Cheetah Template Instantiation and Rendering Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Demonstrates the core `Cheetah.Template` class usage in an interactive Python session. It shows how to define a template string, provide a namespace for placeholders, and render the template. Includes examples of changing placeholder values and re-rendering. ```python from Cheetah.Template import Template templateDef = """ $title $contents ## this is a single-line Cheetah comment and won't appear in the output #* This is a multi-line comment and won't appear in the output blah, blah, blah *# """ nameSpace = {'title': 'Hello World Example', 'contents': 'Hello World!'} t = Template(templateDef, searchList=[nameSpace]) print t # Output: # # Hello World Example # # Hello World! # # print t # print it as many times as you want # Output: [ ... same output as above ... ] nameSpace['title'] = 'Example #2' nameSpace['contents'] = 'Hiya Planet Earth!' print t # Now with different plug-in values. # Output: # # Example #2 # # Hiya Planet Earth! # # ``` -------------------------------- ### Minimal Cheetah Template Instantiation and Rendering Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Presents a concise example of instantiating and rendering a Cheetah template with a static string directly within a single Python statement, demonstrating the simplest usage without placeholders. ```python print Template("Templates are pretty useless without placeholders.") # Output: Templates are pretty useless without placeholders. ``` -------------------------------- ### Run Cheetah Self-Tests Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Command to execute Cheetah's built-in regression tests to verify a successful installation. It's recommended to run this command in a directory where you have write permissions, not the installation directory, to avoid errors related to temporary files. ```Shell cheetah test ``` -------------------------------- ### Cheetah Command-Line Utility Reference Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Documentation for the `cheetah` command-line utility, providing a command-line interface to various housekeeping tasks. It lists the supported subcommands, their arguments, and a brief description of their function. Commands can be abbreviated to their first letter. ```APIDOC cheetah compile [options] [FILES ...] : Compile template definitions cheetah fill [options] [FILES ...] : Fill template definitions cheetah help : Print this help message cheetah options : Print options help message cheetah test : Run Cheetah's regression tests cheetah version : Print Cheetah version number ``` -------------------------------- ### Using a Precompiled Cheetah Template Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Demonstrates how to use a Cheetah template that has been precompiled into a Python module. It shows importing the compiled template class, instantiating it, setting its attributes, and printing the rendered output. ```python from MyPrecompiledTemplate import MyPrecompiledTemplate t = MyPrecompiledTemplate() t.name = "Fred Flintstone" t.city = "Bedrock City" print t ``` -------------------------------- ### Cheetah Template Instantiation with Direct Attribute Assignment Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Shows an alternative method for populating template placeholders by directly assigning values to attributes of the `Template` instance after instantiation. This achieves the same result as using a `searchList`. ```python t2 = Template(templateDef) t2.title = 'Hello World Example!' t2.contents = 'Hello World' print t2 # Output: [ ... same output as the first example above ... ] t2.title = 'Example #2' t2.contents = 'Hello World!' print t2 # Output: [ ... same as Example #2 above ... ] ``` -------------------------------- ### Python Setup for CheetahTemplate Complex Placeholder Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/placeholders.rst This Python script sets up the necessary environment and data structures to demonstrate CheetahTemplate's complex placeholder features. It defines a `DummyClass` with various methods, a `dummyFunc`, and a `defaultTestNameSpace` dictionary containing strings, integers, floats, lists, dictionaries (including nested ones), functions, and objects. This setup allows for testing different placeholder resolutions and method calls within Cheetah templates. ```Python #!/usr/bin/env python from ComplexExample import ComplexExample try: # Python >= 2.2.1 True, False except NameError: # Older Python True, False = (1==1), (1==0) class DummyClass: _called = False def __str__(self): return 'object' def meth(self, arg="arff"): return str(arg) def meth1(self, arg="doo"): return arg def meth2(self, arg1="a1", arg2="a2"): return str(arg1) + str(arg2) def callIt(self, arg=1234): self._called = True self._callArg = arg def dummyFunc(arg="Scooby"): return arg defaultTestNameSpace = { 'aStr':'blarg', 'anInt':1, 'aFloat':1.5, 'aList': ['item0','item1','item2'], 'aDict': {'one':'item1', 'two':'item2', 'nestedDict':{1:'nestedItem1', 'two':'nestedItem2' }, 'nestedFunc':dummyFunc, }, 'aFunc': dummyFunc, 'anObj': DummyClass(), 'aMeth': DummyClass().meth1, '_': lambda x: 'translated ' + x } print ComplexExample( searchList=[defaultTestNameSpace] ) ``` -------------------------------- ### Cheetah Example: Paginated List Processing in Templates Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Demonstrates integrating MondoReport with Cheetah templates for paginated list display. This example assumes the template acts as a Webware servlet, using `$request.field()` to retrieve a 'start' CGI parameter for pagination. It shows how to initialize MondoReport, loop through pages, and handle empty lists using `#unless`. ```Cheetah #from Cheetah.Tools.MondoReport import MondoReport #set $mr = $MondoReport($bigList) #set $start = $request.field("start", 0) #for $o, $a, $b in $mr.page(20, $start) ... do something with $o, $a and $b ... #end for #unless $bigList This is displayed if the original list has no elements. It's equivalent to the "else" part Zope DTML's . #end unless ``` -------------------------------- ### Cheetah Template Basic Syntax Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/intro.rst This example demonstrates fundamental Cheetah templating syntax, including variable substitution ($title) and loop iteration (#for, #end for) to display data from a list of client objects. ```Cheetah Template $title #for $client in $clients #end for
$client.surname, $client.firstname $client.email
``` -------------------------------- ### CheetahTemplate: Practical Import and From Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/inheritanceEtc.rst Provides concrete examples of how to use #import and #from directives in CheetahTemplate, demonstrating various scenarios such as importing entire modules, specific objects, aliasing, and importing multiple items, similar to standard Python usage. ```CheetahTemplate #import math #import math as mathModule #from math import sin, cos #from math import sin as _sin #import random, re #from mx import DateTime # ## Part of Egenix's mx package. ``` -------------------------------- ### APIDOC: webInput() Method and Usage Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/webware.rst Documentation for the `webInput()` method, which simplifies placing specified GET/POST fields, cookies, or session variables into a dictionary and the searchList. It supports single/multiple values, type conversion, default values, and exception handling. Includes basic usage examples within Cheetah templates. ```APIDOC def webInput(self, names, namesMulti=(), default='', src='f', defaultInt=0, defaultFloat=0.00, badInt=0, badFloat=0.00, debug=False): This method places the specified GET/POST fields, cookies or session variables into a dictionary, which is both returned and put at the beginning of the searchList. It handles: * single vs multiple values * conversion to integer or float for specified names * default values/exceptions for missing or bad values * printing a snapshot of all values retrieved for debugging All the 'default*' and 'bad*' arguments have "use or raise" behavior, meaning that if they're a subclass of Exception, they're raised. If they're anything else, that value is substituted for the missing/bad value. ``` ```Cheetah The simplest usage is: #silent $webInput(['choice']) $choice dic = self.webInput(['choice']) write(dic['choice']) Both these examples retrieves the GET/POST field 'choice' and print it. If you ``` -------------------------------- ### MondoReport.query() Method for HTML Hyperlink Generation Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Documents the `query` method of `MondoReport` instances, used to generate HTML hyperlinks. It explains how to specify the link label, attribute name for the 'start' parameter, and additional HTML attributes. This method assumes 'start' is a GET variable. ```APIDOC MondoReport.query(label=None, attribName="start", attribs={}, before="", after="") label: (string, optional) The text label for the hyperlink. If specified, returns a complete HTML hyperlink. attribName: (string, optional) The name of the CGI parameter for the 'start' value, defaults to "start". attribs: (dictionary, optional) A dictionary of additional HTML attributes to add to the hyperlink (e.g., {"target": "_blank"}). Ignored unless 'label' is specified. before: (string, optional) Text prepended to the returned HTML. after: (string, optional) Text appended to the returned HTML. Returns: A complete HTML hyperlink string. Assumptions: The 'start' parameter is a GET variable. ``` -------------------------------- ### CheetahTemplate/Python: Multi-Layered Site Inheritance Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/inheritanceEtc.rst A comprehensive example showcasing a complex inheritance hierarchy for a web application, integrating pure Python classes with CheetahTemplate files to build a structured site. It demonstrates how different components inherit from each other to form a complete system, from base site logic to specific page logic. ```Python from Cheetah.Template import Template class SiteLogic(Template): ``` ```CheetahTemplate #from SiteLogic import SiteLogic #extends SiteLogic #implements respond ``` ```Python from Site import Site class SectionLogic(Site) ``` ```CheetahTemplate #from SectionLogic import SectionLogic #extends SectionLogic ``` ```Python from Section import Section class indexLogic(Section): ``` -------------------------------- ### CheetahTemplate Processed Output Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/placeholders.rst This snippet shows the rendered output when the complex CheetahTemplate placeholders are processed using the provided Python setup. It demonstrates how placeholders are resolved to their corresponding values, including strings, integers, and the results of function calls, illustrating the final rendered template content. ```Plain Text 1 placeholder: blarg 2 placeholders: blarg 1 2 placeholders, back-to-back: blarg1 1 placeholder enclosed in {}: blarg 1 escaped placeholder: $var func placeholder - with (): Scooby ``` -------------------------------- ### Cheetah Template Instantiation via Subclassing Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/gettingStarted.rst Illustrates another flexible way to define template data by subclassing the `Template` class and setting placeholder values as class attributes. This approach can be useful for defining reusable template structures. ```python class Template3(Template): title = 'Hello World Example!' contents = 'Hello World!' t3 = Template3(templateDef) print t3 # Output: [ ... you get the picture ... ] ``` -------------------------------- ### Basic Cheetah Template Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/recipes/precompiled.rst A simple Cheetah template file (`hello.tmpl`) demonstrating the use of `#attr` for defining template attributes and `${variable}` for variable substitution within HTML structure. ```Cheetah Template #attr title = "This is my Template" ${title} Hello ${who}! ``` -------------------------------- ### CheetahTemplate Variable and Directive Syntax Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/language.rst Demonstrates common CheetahTemplate syntax for variable access and directive usage, including local variable creation, loops, imports, method definitions, and accessing template instance attributes. ```CheetahTemplate #set #for #import #from ... import #def #block methods $myInstance.fname $myAttr $self.myAttr ``` -------------------------------- ### Cheetah Template: Change Variable Start Token with #compiler-settings Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/parserInstructions.rst This example demonstrates how to use '#compiler-settings' to change the default variable start token from '$' to '@'. After the settings block, variables are accessed using the new token, and then reset to the default. ```Cheetah Template $myVar #compiler-settings cheetahVarStartToken = @ #end compiler-settings @myVar #compiler-settings reset $myVar ``` -------------------------------- ### PrevNextPage Instance Methods for Pagination Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Documents the core methods available on `PrevNextPage` instances, which are used for pagination. This includes methods to retrieve the start and end indices of the current page, the number of records on the page, and a specialized query method for generating pagination links. ```APIDOC PrevNextPage .start() Returns: The true index of origList where the page starts. Can be used with .index(), .number(), .item(field=None). .end() Returns: The true index of origList where the page ends. Can be used with .index(), .number(), .item(field=None). .length() Returns: The number of records on the current page. .query(label=None, attribName="start", attribs={}, before="", after="") Description: Similar to MondoReport.query(), but automatically calculates the 'start' value for the appropriate page. label: (string, optional) The text label for the hyperlink. attribName: (string, optional) The name of the CGI parameter for the 'start' value, defaults to "start". attribs: (dictionary, optional) A dictionary of additional HTML attributes. before: (string, optional) Text prepended to the returned HTML. after: (string, optional) Text appended to the returned HTML. Returns: A complete HTML hyperlink string for pagination. ``` -------------------------------- ### CheetahTemplate: Extends Directive Implicit Import Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/inheritanceEtc.rst Demonstrates how CheetahTemplate automatically handles implicit imports when the #extends directive is used, showing the equivalent #from statements that are generated behind the scenes for common inheritance scenarios. ```CheetahTemplate #extends Superclass ## Implicitly does '#from Superclass import Superclass'. #extends Cheetah.Templates.SkeletonPage ## Implicitly does '#from Cheetah.Templates.SkeletonPage import SkeletonPage'. ``` -------------------------------- ### Install Cheetah from Source Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/patching.rst Command to install Cheetah from a source distribution, typically used after making changes in a CVS sandbox to apply modifications for testing. ```shell python setup.py install ``` -------------------------------- ### CheetahTemplate Complex Placeholder Syntax Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/placeholders.rst This section provides a comprehensive list of complex placeholder syntaxes supported by CheetahTemplate. It covers simple variables, multiple placeholders, escaped placeholders, function calls with various argument types (including nested calls), Python built-in values, autocalling, list/dictionary access (both NameMapper and Python styles), object method calls, and internationalization (`_`). These examples illustrate the flexibility of Cheetah's templating language. ```CheetahTemplate Syntax 1 placeholder: $aStr 2 placeholders: $aStr $anInt 2 placeholders, back-to-back: $aStr$anInt 1 placeholder enclosed in {}: ${aStr} 1 escaped placeholder: \$var func placeholder - with (): $aFunc() func placeholder - with (int): $aFunc(1234) func placeholder - with (string): $aFunc('aoeu') func placeholder - with ('''\nstring'\n'''): $aFunc('''\naoeu'\n''') func placeholder - with (string*int): $aFunc('aoeu'*2) func placeholder - with (int*float): $aFunc(2*2.0) Python builtin values: $None $True $False func placeholder - with ($arg=float): $aFunc($arg=4.0) deeply nested argstring: $aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ): function with None: $aFunc(None) autocalling: $aFunc! $aFunc(). nested autocalling: $aFunc($aFunc). list subscription: $aList[0] list slicing: $aList[:2] list slicing and subcription combined: $aList[:2][0] dict - NameMapper style: $aDict.one dict - Python style: $aDict['one'] dict combined with autocalled string method: $aDict.one.upper dict combined with string method: $aDict.one.upper() nested dict - NameMapper style: $aDict.nestedDict.two nested dict - Python style: $aDict['nestedDict']['two'] nested dict - alternating style: $aDict['nestedDict'].two nested dict - NameMapper style + method: $aDict.nestedDict.two.upper nested dict - alternating style + method: $aDict['nestedDict'].two.upper nested dict - NameMapper style + method + slice: $aDict.nestedDict.two.upper[:4] nested dict - Python style, variable key: $aDict[$anObj.meth('nestedDict')].two object method: $anObj.meth1 object method + complex slice: $anObj.meth1[0: ((4/4*2)*2)/$anObj.meth1(2) ] very complex slice: $( anObj.meth1[0: ((4/4*2)*2)/$anObj.meth1(2) ] ) $_('a call to gettext') ``` -------------------------------- ### Cheetah.ErrorCatchers.BigEcho Output Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/errorHandling.rst Demonstrates the output format when using the `Cheetah.ErrorCatchers.BigEcho` subclass of `ErrorCatcher`. Unlike `Echo`, `BigEcho` provides a more verbose and visually distinct warning message for missing placeholders in the template output. ```Cheetah Here's a good placeholder: Here I am! Here's bad placeholder: ===============<$iDontExist could not be found>=============== ``` -------------------------------- ### Cheetah.Servlet API Reference Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/tipsAndTricks.rst Base class for Cheetah templates used as Webware servlets, providing core lifecycle methods and access to Webware transaction objects. It exposes attributes for checking transaction status, Webware installation, and direct access to Webware's request, response, and session objects. ```APIDOC Cheetah.Servlet: - isLiveTransaction: bool True if this template instance is part of a live transaction in a running WebKit servlet. - isWebwareInstalled: bool True if Webware is installed and the template instance inherits from WebKit.Servlet. If not, it inherits from Cheetah.Servlet.DummyServlet. - awake(): None Called by WebKit at the beginning of the web transaction. (Can be overridden, but call superclass method.) - sleep(): None Called by WebKit at the end of the web transaction. (Can be overridden, but call superclass method.) - respond(): None Called by WebKit to produce the web transaction content. For a template-servlet, this means filling the template. - __del__(): None Break reference cycles before deleting instance. - serverSidePath: str The filesystem pathname of the template-servlet (as opposed to the URL path). - transaction: WebwareTransaction The current Webware transaction. - application: WebwareApplication The current Webware application. - response: WebwareResponse The current Webware response. - request: WebwareRequest The current Webware request. - session: WebwareSession The current Webware session. - write(text: str): None Call this method to insert text in the filled template output. ``` -------------------------------- ### WebKit.Servlet API Reference (Inherited) Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/tipsAndTricks.rst Core WebKit servlet attributes and methods inherited by Cheetah servlets, primarily for logging, debugging, and servlet lifecycle management. These are accessible only if Webware is installed. ```APIDOC WebKit.Servlet: - name: str The simple name of the class. Used by Webware's logging and debugging routines. - description: str Used by Webware's logging and debugging routines. - isMultithreaded: bool True if the servlet can be multithreaded. - isReusable: bool True if the servlet can be used for another transaction after the current transaction is finished. - path: str Depreciated by .serverSidePath(). ``` -------------------------------- ### Cheetah Looping and Manual Even/Odd Row Styling with #for Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/comparisons.rst This Cheetah example shows how to loop through a list of files using the `#for` directive. It manually manages an `$evenRow` variable to achieve alternating row colors, demonstrating a common approach when built-in sequence helpers are not available or preferred. ```Cheetah #set $evenRow = 0 #for $file in $files('File') #if $evenRow #set $evenRow = 0 #else #set $evenRow = 1 #end if #end for
$file.title_or_id
``` -------------------------------- ### Python Example: Iterating Through Paginated Records Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Illustrates how to use MondoReport in Python to iterate through a paginated list. It shows importing the class, creating an instance, and looping through records returned by the `.page()` method. Includes a check for an empty list. ```Python from Cheetah.Tools.MondoReport import MondoReport mr = MondoReport(myList) for r, a, b in mr.page(20, 40): # Do something with r, a and b. The current page is the third page, # with twenty records corresponding to origList[40:60]. if not myList: # Warn the user there are no records in the list. ``` -------------------------------- ### Cheetah Template Valid and Invalid Placeholder Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/language.rst Demonstrates correctly formed Cheetah placeholders, including those with underscores, numbers, attribute access, and method calls. It also provides examples of text that are not recognized as placeholders by Cheetah. ```Cheetah Template $a $_ $var $_var $var1 $_1var $var2_ $dict.key $list[3] $object.method $object.method() $object.method $nest($nest($var)) ``` ```Cheetah Template $@var $^var $15.50 $$ ``` -------------------------------- ### DTML and Cheetah Iteration Syntax Comparison Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/comparisons.rst These snippets illustrate how to iterate over a collection (e.g., `frogQuery`) in both DTML and Cheetah template languages. The DTML example uses `dtml-in` and `dtml-var`, while the Cheetah example uses a Python-like `#for` loop with `$variable` syntax. ```DTML ``` ```Cheetah ``` -------------------------------- ### Dynamic Main Method Lookup for Cheetah Templates Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/recipes/precompiled.rst Advanced Python example showing how to dynamically retrieve and execute the main rendering method of a precompiled Cheetah template. This approach is useful when the `#implements` directive is used, which might change the default `respond` method. ```Python def myMethod(): tmpl = hello.hello(searchList=[{'who' : 'world'}]) mainMethod = getattr(tmpl, '_mainCheetahMethod_for_%s' % tmpl.__class__.__name__) results = getattr(tmpl, mainMethod)() ``` -------------------------------- ### Iterating with MondoReport.page() for Pagination Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Illustrates how to iterate over paginated results returned by `MondoReport.page()`. Examples are provided for both Python and CheetahTemplate syntax, showing how to unpack the returned tuples containing key-value pairs and BatchRecord instances (`a`, `b`). ```Python for (key, value), a, b in mr.page(20, 40): print key, "=>", value ``` ```CheetahTemplate #for ($key, $value), $a, $b in $mr.page(20, $start) $key => $value #end for ``` -------------------------------- ### Velocity Context Population Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/comparisons.rst This Java code snippet demonstrates how to manually populate a `VelocityContext` object using its `.put()` method. It shows how key-value pairs are added to the context, which serves as the namespace for template variables in Velocity. ```Java VelocityContext context1 = new VelocityContext(); context1.put("name","Velocity"); context1.put("project", "Jakarta"); context1.put("duplicate", "I am in context1"); ``` -------------------------------- ### Cheetah Docstring Comments Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/comments.rst Examples of various Cheetah comment prefixes that transform template comments into Python docstrings for modules, classes, and methods. These docstrings are accessible at runtime in the generated Python code, providing inline documentation. ```Cheetah ##doc: This text will be added to the method docstring #*doc: If your template file is MyTemplate.tmpl, running "cheetah compile" on it will produce MyTemplate.py, with a class MyTemplate in it, containing a method .respond(). This text will be in the .respond() method's docstring. *# ##doc-method: This text will also be added to .respond()'s docstring #*doc-method: This text will also be added to .respond()'s docstring *# ##doc-class: This text will be added to the MyTemplate class docstring #*doc-class: This text will be added to the MyTemplate class docstring *# ##doc-module: This text will be added to the module docstring MyTemplate.py #*doc-module: This text will be added to the module docstring MyTemplate.py*# ``` -------------------------------- ### Cheetah Template Syntax for CGI Script Headers Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/otherHtml.rst These examples demonstrate how to configure a Cheetah template to act as a CGI script. By extending `Cheetah.Tools.CGITemplate` or a custom Python class that inherits from it, and implementing the `respond` method, the template can automatically output necessary CGI headers using `$cgiHeaders#slurp`. ```CheetahTemplate #extends Cheetah.Tools.CGITemplate #implements respond $cgiHeaders#slurp ``` ```CheetahTemplate #extends MyPythonClass #implements respond $cgiHeaders#slurp ``` -------------------------------- ### Basic Cheetah Template for Dynamic Content Generation Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/index.rst This example illustrates a fundamental Cheetah template, demonstrating its Python-like syntax for variable assignment, iteration over a list of dictionaries, and embedding dynamic content within HTML. It showcases how Cheetah templates can be used to generate structured output by combining template directives with standard HTML. ```Cheetah Template #from Cheetah.Template import Template #extends Template #set $people = [{'name' : 'Tom', 'mood' : 'Happy'}, {'name' : 'Dick', 'mood' : 'Sad'}, {'name' : 'Harry', 'mood' : 'Hairy'}] How are you feeling? ``` -------------------------------- ### CheetahTemplate Variable Access Examples Source: https://github.com/cheetahtemplate/cheetah/blob/master/cheetah/Tools/MondoReportDoc.txt Demonstrates various ways to access attributes and keys of a variable `$r` within CheetahTemplate, including direct attribute access, dictionary-style key access, and chained method/attribute calls. The `##` syntax indicates comments. ```CheetahTemplate ## 'name' is a function or method, it will be called without ## arguments. $r.attribute $r['key'] $r $r().attribute()['key']() ``` -------------------------------- ### PSP: Accessing Nested Data Structures Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/language.rst An example of accessing deeply nested data (customer's city from address) using Page Server Pages (PSP) syntax. This illustrates a more verbose and complex approach compared to Cheetah's NameMapper for similar data access scenarios. ```PSP <%= self.customer()[ID].address()['city'] %> ``` -------------------------------- ### Cheetah Template: NameMapper Syntax for Data Access Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/language.rst These examples showcase the flexibility and simplification offered by Cheetah's NameMapper syntax for accessing nested data structures. They demonstrate various equivalent forms, including omitting `self` and using dotted notation for method calls and dictionary access, making the code more readable and accessible for non-programmers. ```Cheetah Template $self.customers()[$ID].address()['city'] ``` ```Cheetah Template $customers()[$ID].address()['city'] ``` ```Cheetah Template $customers()[$ID].address().city ``` ```Cheetah Template $customers()[$ID].address.city ``` ```Cheetah Template $customers[$ID].address.city ``` -------------------------------- ### Cheetah Template Webware Servlet with Form Handling Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/intro.rst An example of a Webware servlet utilizing Cheetah templates to create an interactive web page. It demonstrates conditional rendering (#if, #else), variable assignment (#set), and accessing request parameters ($request.field) to display a personalized greeting based on user input from an HTML form. ```Cheetah Template My Template-Servlet #set $name = $request.field('name', None) #if $name Hello $name #else
Name:
#end if ``` -------------------------------- ### Cheetah Template: Change Directive Start Token with #compiler-settings Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/parserInstructions.rst This example shows how to change the directive start token from '#' to '%' using '#compiler-settings'. Directives within the block will use the new prefix, which is then reset to the default. ```Cheetah Template #slurp #compiler-settings directiveStartToken = % #end compiler-settings %slurp %compiler-settings reset #slurp ``` -------------------------------- ### webInput Method Reference Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/webware.rst Detailed documentation for the `webInput` method, outlining its parameters, behavior for single and multi-valued inputs, type conversion capabilities, and error handling. It also lists common sources for input values and how default/bad value arguments are handled. ```APIDOC webInput( single_values: list = [], multi_values: list = [], source: str = 'f', default: str = "", badInt: any = 0, badFloat: any = 0, defaultInt: any = 0, defaultFloat: any = 0, debug: bool = False ) -> dict Parameters: single_values (list): A list of strings, each representing a single-valued input name. Can include type suffixes like 'name:int' or 'name:float'. - If one value is found, it's taken. - If several values are found, one is chosen arbitrarily. - If no values are found, 'default*' is used or an error raised. multi_values (list): A list of strings, each representing a multi-valued input name. - If one or more values are found, they are put in a list. - If no values are found, an empty list ([]) is returned. 'default*' arguments are NOT consulted. source (str): Specifies the source of the input values. - 'f': fields (CGI GET/POST parameters) - 'c': cookies - 's': session variables - 'v': "values" (fields or cookies) default (str): Default value for missing string inputs. Defaults to "". badInt (any): Value to use for 'bad' integer conversions. Defaults to 0. Can be None, a constant, $NonNumericInputError, or $ValueError. badFloat (any): Value to use for 'bad' float conversions. Defaults to 0. Can be None, a constant, $NonNumericInputError, or $ValueError. defaultInt (any): Default value for missing integer inputs. Defaults to 0. defaultFloat (any): Default value for missing float inputs. Defaults to 0. debug (bool): If True, pretty-prints all values inside HTML
 tags.

Returns:
  dict: A dictionary containing the processed input values.

Error Handling:
  - NonNumericInputError: Raised for non-numeric characters when numeric conversion is specified.
  - ValueError: Can be raised for other conversion issues.
```

--------------------------------

### PSP Template Syntax Comparison

Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/intro.rst

This snippet provides a direct comparison of templating syntax with PSP (Python Server Pages), illustrating how similar logic for displaying client data is expressed using PSP's <%= %> for variables and <% %> for control flow.

```PSP Template

<%=title%>



<% for client in clients: %>

<%end%>
<%=client['surname']%>, <%=client['firstname']%> <%=client['email']%>
``` -------------------------------- ### Generated Python Module for 'Hello, world!' Template Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/pyModules.rst The complete Python source code of the template module automatically generated by Cheetah from the 'Hello, world!' template. This module defines the `x` class, which inherits from `Cheetah.Template.Template`, and includes the `__init__` and `respond` methods responsible for template initialization and rendering. It demonstrates the boilerplate and logic Cheetah adds to make a template executable. ```Python #!/usr/bin/env python """ Autogenerated by CHEETAH: The Python-Powered Template Engine CHEETAH VERSION: 0.9.12 Generation time: Sat Apr 20 14:27:47 2002 Source file: x.tmpl Source file last modified: Wed Apr 17 22:10:59 2002 """ __CHEETAH_genTime__ = 'Sat Apr 20 14:27:47 2002' __CHEETAH_src__ = 'x.tmpl' __CHEETAH_version__ = '0.9.12' ################################################## ## DEPENDENCIES import sys import os import os.path from os.path import getmtime, exists import time import types from Cheetah.Template import Template from Cheetah.DummyTransaction import DummyTransaction from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers ################################################## ## MODULE CONSTANTS try: True, False except NameError: True, False = (1==1), (1==0) ################################################## ## CLASSES class x(Template): """ Autogenerated by CHEETAH: The Python-Powered Template Engine """ ################################################## ## GENERATED METHODS def __init__(self, *args, **KWs): """ """ Template.__init__(self, *args, **KWs) self._filePath = 'x.tmpl' self._fileMtime = 1019106659 def respond(self, trans=None, dummyTrans=False, VFS=valueFromSearchList, VFN=valueForName, getmtime=getmtime, currentTime=time.time): """ This is the main method generated by Cheetah """ if not trans: trans = DummyTransaction() dummyTrans = True write = trans.response().write SL = self._searchList filter = self._currentFilter globalSetVars = self._globalSetVars ######################################## ## START - generated method body if exists(self._filePath) and getmtime(self._filePath) > self._fileMtime: self.compile(file=self._filePath) write(getattr(self, self._mainCheetahMethod_for_x)(trans=trans)) if dummyTrans: return trans.response().getvalue() else: return "" write('Hello, world!\n') ######################################## ## END - generated method body if dummyTrans: return trans.response().getvalue() else: return "" ################################################## ## GENERATED ATTRIBUTES __str__ = respond _mainCheetahMethod_for_x= 'respond' # CHEETAH was developed by Tavis Rudd, Chuck Esterbrook, Ian Bicking and Mike Orr; # with code, advice and input from many other volunteers. # For more information visit http://www.CheetahTemplate.org ################################################## ## if run from command line: if __name__ == '__main__': x().runAsMainProgram() ``` -------------------------------- ### Cheetah Template: Change Comment Start Token with #compiler-settings Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/parserInstructions.rst This snippet illustrates how to modify the comment start token from '##' to '//' using '#compiler-settings'. Comments within the block will use the new style, which is then reverted to the default. ```Cheetah Template ## normal comment #compiler-settings commentStartToken = // #end compiler-settings // new style of comment #compiler-settings reset ## back to normal comments ``` -------------------------------- ### Basic Cheetah Template Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/dev_guide/pyModules.rst A basic 'Hello, world!' template demonstrating the simplest form of a Cheetah template file. This minimal template directly outputs the specified text. ```Cheetah Template Hello, world! ``` -------------------------------- ### Looping and Data Display in Template Engines Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/comparisons.rst Compares the syntax for iterating over data and displaying client information within an HTML table using both Cheetah and PSP template engines. This demonstrates the different syntactical approaches for embedding control flow and variable output in each system. ```Cheetah #for $client in $service.clients #end for
$client.surname, $client.firstname $client.email
``` ```PSP <% for client in service.clients(): %> <%end%>
<%=client.surname()%>, <%=client.firstname()%> <%=client.email()%>
``` -------------------------------- ### Accessing CGI GET/POST Parameters in Cheetah Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/webware.rst Demonstrates how to retrieve single CGI GET or POST parameters using the `$request.field()` or `self.request().field()` methods. Note that POST parameters will override GET parameters if both are present. ```Cheetah $request.field('myField') self.request().field('myField') ``` -------------------------------- ### CheetahTemplate Nested Block Directive Example Source: https://github.com/cheetahtemplate/cheetah/blob/master/www/users_guide/inheritanceEtc.rst Illustrates the nesting capability of the `#block` directive in CheetahTemplate, showing how `innerBlock1` and `innerBlock2` are contained within `outerBlock`. The example also highlights that the block name is optional for the `#end block` tag. ```CheetahTemplate #block outerBlock Outer block contents #block innerBlock1 inner block1 contents #end block innerBlock1 #block innerBlock2 inner block2 contents #end block innerBlock2 #end block outerBlock ```