"Fossies" - the Fresh Open Source Software Archive

Member "cheetah3-3.2.6.post2/docs/recipes/staticmethod.rst" (20 Apr 2021, 2318 Bytes) of package /linux/www/cheetah3-3.2.6.post2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format (assuming markdown format). Alternatively you can here view or download the uninterpreted source code file. A member file download can also be achieved by clicking within a package contents listing on the according byte size field.

@staticmethod and @classmethod

Refer the Python's documentation if you're unfamiliar with either @staticmethod or @classmethod and their uses in Python, as they pertain to their uses in Cheetah as well. Using @staticmethod it's trivial to create utility templates which are common when using Cheetah for web development. These utility templates might contain a number of small functions which generate useful snippets of markup.

For example:

#def copyright()
    #import time
    © CheetahCorp, Inc. $time.strftime('%Y', time.gmtime())
#end def

Figure 1, util.tmpl

Prior to version v2.2.0 of Cheetah, there wasn't really an easy means of filling templates with bunches of these small utility functions. In v2.2.0 however, you can decorate these methods with #@staticmethod and use "proper" Python syntax for calling them, fig 1 revisited:

#@staticmethod
#def copyright()
    #import time
    © CheetahCorp, Inc. $time.strftime('%Y', time.gmtime())
#end def

Figure 1.1, util.tmpl

With the addition of the @staticmethod decorator, the copyright() function can now be used without instantiating an instance of the util template class. In effect:

#from util import util

<strong>This is my page</strong>
<br/>
<hr noshade/>
$util.copyright()

Figure 2, index.tmpl

This approach is however no means to structure anything complex, @staticmethod and @classmethod use in Cheetah is not meant as a replacement for properly structured class hierarchies (which Cheetah supports). That said if you are building a web application @staticmethod/@classmethod are quite useful for the little snippets of markup, etc that are needed (Google AdSense blocks, footers, banners, etc).