Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Changes between Version 1 and Version 2 of TurboCheetahTemplates


Ignore:
Timestamp:
06/29/07 11:40:14 (12 years ago)
Author:
Chris Arndt
Comment:

migration notice

Legend:

Unmodified
Added
Removed
Modified
  • TurboCheetahTemplates

    v1 v2  
    1 = Templates for using !TurboCheetah with TurboGears = 
    2  
    3 Author: [http://chrisarndt.de Christopher Arndt] 
    4  
    5 So you want to use Cheetah templates for your pages but still take advantage of the automatic Javascript/CSS inclusion that the standard Kid sitetemplate does? Here are the files you need to set up a mini TurboGears project using [http://www.turbogears.org/docs/plugins/template.html TurboCheetah]. 
    6  
    7 == The main controller == 
    8  
    9 We are going to test our templates with this minimal controller. Just replace the contents of `controllers.py` of our fresh, quickstarted project with this code: 
    10  
    111{{{ 
    12 # -*- coding: UTF-8 -*- 
    13  
    14 import cherrypy 
    15  
    16 import turbogears 
    17 from turbogears import controllers, expose 
    18  
    19 class Root(controllers.RootController): 
    20     @expose(template="cheetah:cheetahtemplates.templates.welcome") 
    21     def index(self): 
    22         import time 
    23         turbogears.flash(u"Herzliche Grüße & viel Spaß!") 
    24         return dict(now=time.ctime()) 
     2#!rst 
     3.. note:: This page has been migrated to http://docs.turbogears.org/1.0/AdvancedCheetahTemplates. 
    254}}} 
    26  
    27 Note the encoding declaration at the top of the file, so that we can use UTF-8 characters in our unicode strings. Make sure to save this file with UTF-8 encoding. Replace `cheetahtemplates` in the template name with the package name of your project. 
    28  
    29 == The template base class == 
    30  
    31 With Cheetah your templates can subclass a pure Python class. Attributes and functions of this class are available as template variables. This allows to define some handy utility functions for using in our templates and also to implement a fix for Cheetah's unicode handling. 
    32  
    33 {{{ 
    34 from cgi import escape 
    35 from Cheetah.Filters import Filter 
    36 from Cheetah.Template import Template 
    37 from turbogears import url 
    38  
    39 class HSC(Filter): 
    40     """A filter for Cheetah placeholder substitution supporting unicode objects. 
    41  
    42     Supports the following arguments: 
    43  
    44     escape    - if evaluates to True, escape the placeholder substitution 
    45                 with cgi.escape. If escape == 'quote', the 'quote' parameter of 
    46                 cgi.escape is set to True). 
    47     maxlength - if set to an int > 0, truncate the placeholder substitution at 
    48                 maxlength characters, possibly replacing the end with suffix. 
    49     suffix    - when truncating the placeholder to maxlength, replace the last 
    50                 len(suffix) characters with suffix (defaults to '...'). 
    51     """ 
    52  
    53     def filter(self, val, **kw): 
    54         if val is None: 
    55             return '' 
    56         elif isinstance(val, unicode): 
    57             val = val.encode(kw.get('encoding', 'utf-8')) 
    58         val = str(val) 
    59         if kw.get('escape', False): 
    60             val = escape(val, kw.get('escape') == 'quote') 
    61         if kw.get('maxlength'): 
    62             try: 
    63                 length = int(kw['maxlength']) 
    64             except ValueError: pass 
    65             else: 
    66                 suffix = kw.get('suffix', '...') 
    67                 if len(val) > length and suffix: 
    68                     length -= len(suffix) 
    69                     val = val[:length] + suffix 
    70                 else: 
    71                     val = val[:length] 
    72         return val 
    73  
    74 class SiteBase(Template): 
    75  
    76     image_base = url('/static/images/') 
    77     css_base = url('/static/css/') 
    78     js_base = url('/static/javascript/') 
    79  
    80     _js_src_tmpl = '<script type="text/javascript" language="JavaScript%s">\n%s</script>' 
    81  
    82     _js_link_tmpl = '<script type="text/javascript" language="JavaScript%s" src="%s"></script>' 
    83  
    84     _css_link_tmpl = '<link rel="%s" type="text/css" href="%s" />' 
    85  
    86     def __init__(self, *args, **kw): 
    87         """Constructor sets the default filter to use.""" 
    88  
    89         kw['filter'] = HSC 
    90         Template.__init__(self, *args, **kw) 
    91  
    92     def js_link(self, relpath, version=''): 
    93         return self._js_link_tmpl % (version, self.js_base + relpath) 
    94  
    95     def js_src(self, relpath, version=''): 
    96         return self._js_src_tmpl % (version, self.js_base + relpath) 
    97  
    98     def css_link(self, relpath, type="stylesheet"): 
    99         return self._css_link_tmpl % (type, self.css_base + relpath) 
    100 }}} 
    101  
    102 Save this file as `SiteBase.py` in the `templates` folder of your project (the exact name is important). You can delete the Kid templates, since we will not use them for our mini project. Don't delete the `__init__.py` file. 
    103  
    104 The custom filter `HSC` class implements unicode support for Cheetah up to version 2.0rc6. Newer versions come with a new standard filter that should support unicode out-of-the-box. 
    105  
    106 == The site template == 
    107  
    108 This defines the basic layout of all your pages. Customise to your liking or plug in another template in the inheritance structure. See the Cheetah user guide for more information. '''Be sure to always include the meta header that sets the page encoding to UTF-8.''' 
    109  
    110 {{{ 
    111 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    112 #extends SiteBase 
    113 #implements respond 
    114 <html> 
    115 <head> 
    116     #block headtop 
    117     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    118     #end block 
    119  
    120     #for $css in $tg_css 
    121     ## normally you should be able to just use 
    122     ## $css.render() 
    123     ## but for some reasons that does not work for me 
    124     ${getattr(css, 'render')()} 
    125     #end for 
    126  
    127     ## include your own external CSS stylesheet links here, e.g. 
    128     ##$css_link('myproject.css') 
    129  
    130     #for $js in $tg_js_head 
    131     ${getattr(js, 'render')()} 
    132     #end for 
    133  
    134     ## include your own external JS files here links here, e.g. 
    135     ##$js_link('myproject.js') 
    136  
    137     #block pagetitle 
    138     <title></title> 
    139     #end block 
    140 </head> 
    141  
    142 <body> 
    143 #for $js in $tg_js_bodytop 
    144 ${getattr(js, 'render')()} 
    145 #end for 
    146  
    147 <div id="header"> 
    148     #if $tg.config('identity.on', False) 
    149     <div id="pageLogin"> 
    150         #if $tg.identity.anonymous 
    151         You are not logged in 
    152             #if 'loggin_in' not in locals() 
    153             <span class="menu-sep">::</span> 
    154             <a href="$tg.url('/login')">Login</a> 
    155             #end if 
    156         #else 
    157         You are logged in as 
    158         <span class="user_name">$tg.identity.user.display_name</span> 
    159         <span class="menu-sep">::</span> 
    160         <a href="$tg.url('/logout')">Logout</a> 
    161         #end if 
    162         <span class="menu-sep">::</span> 
    163         <a href="$tg.url('/')">Home</a> 
    164     </div> 
    165     #end if 
    166 </div> 
    167  
    168 #if $tg_flash 
    169 <div class="tg_flash">${tg_flash, escape=True}</div> 
    170 #end if 
    171  
    172 <div id="pagecontent"> 
    173 #block pagecontent 
    174 <p class="placeholder">Here comes the page content...</p> 
    175 #end block 
    176 </div> 
    177  
    178 #for $js in $tg_js_bodybottom 
    179 ${getattr(js, 'render')()} 
    180 #end for 
    181 </body> 
    182 </html> 
    183 }}} 
    184  
    185 Save this file as `SiteTemplate.tmpl` in the `templates` folder of your project and compile it with `cheetah-compile SiteTemplate.py`. 
    186  
    187 == The page template == 
    188  
    189 Finally, here's an example for a page template. Note how we just write the actual content of the page by redefining the `pagecontent` block with the `#def` directive. All the rest of the HTML comes from `SiteTemplate`. 
    190  
    191 {{{ 
    192 #extends cheetahtemplates.templates.SiteTemplate 
    193  
    194 #def pagetitle 
    195     <title>Welcome to TurboGears!</title> 
    196 #end def 
    197  
    198 #def pagecontent 
    199 <h1>Welcome to TurboGears!</h1> 
    200  
    201 <p>This page was generated on $now</p> 
    202 #end def 
    203 }}} 
    204  
    205 Save this file as `welcome.tmpl` in the `templates` folder of your project. Again, replace `cheetahtemplates` in the `#extends` directive with the package name of your project. 
    206  
    207 == Testing == 
    208  
    209 Now start your Turbogears server and open your browser at `http://localhost:8080`. You should see a page with "Herzliche Grüße & viel Spaß!" at the top and the current date & time in place of the `$now` placeholder. 
    210  
    211 == Conclusion == 
    212  
    213 Here's a recap of the most important things to remember: 
    214  
    215  * Prefix your template name in `@expose` with `cheeath:` 
    216  * Compile your Cheetah site template with `cheetah-compile`, since TurboGears does not do this automatically as it does with Kid templates. 
    217  * Put a meta header declaring the UTF-8 encoding for the HTML output in your site template. 
    218  * Put an encoding declaration for UTF-8 in your python source files if you use literal unicode strings and save them UTF-8 encoded. 
    219  * Put any complex function you want to use in all your templates as methods in the `SiteBase` class. 
    220  * If your template variables may contain special HTML characters, use the `escape` parameter for placeholders, e.g. `${myvar, escape=True}`