Debian Codegraph @

docs/recipes/staticmethod.rst

raw
1 @staticmethod and @classmethod
2 ==============================
3
4 Refer the Python's documentation if you're unfamiliar with either
5 `@staticmethod <http://docs.python.org/library/functions.html#staticmethod>`_ or
6 `@classmethod <http://docs.python.org/library/functions.html#classmethod>`_ and their uses in Python, as they
7 pertain to their uses in Cheetah as well. Using `@staticmethod <http://docs.python.org/library/functions.html#staticmethod>`_ it's
8 trivial to create *utility templates* which are common when using
9 Cheetah for web development. These *utility templates* might contain
10 a number of small functions which generate useful snippets of markup.
11
12 For example::
13
14 #def copyright()
15 #import time
16 &copy; CheetahCorp, Inc. $time.strftime('%Y', time.gmtime())
17 #end def
18
19 **Figure 1, util.tmpl**
20
21 Prior to version **v2.2.0** of Cheetah, there wasn't really an easy means
22 of filling templates with bunches of these small utility functions. In
23 **v2.2.0** however, you can decorate these methods with `#@staticmethod`
24 and use "proper" Python syntax for calling them, **fig 1** revisited::
25
26 #@staticmethod
27 #def copyright()
28 #import time
29 &copy; CheetahCorp, Inc. $time.strftime('%Y', time.gmtime())
30 #end def
31
32 **Figure 1.1, util.tmpl**
33
34 With the addition of the `@staticmethod <http://docs.python.org/library/functions.html#staticmethod>`_ decorator, the `copyright()`
35 function can now be used without instantiating an instance of the `util`
36 template class. In effect::
37
38 #from util import util
39
40 <strong>This is my page</strong>
41 <br/>
42 <hr noshade/>
43 $util.copyright()
44
45 **Figure 2, index.tmpl**
46
47
48 This approach is however no means to structure anything complex,
49 `@staticmethod <http://docs.python.org/library/functions.html#staticmethod>`_ and `@classmethod <http://docs.python.org/library/functions.html#classmethod>`_ use in Cheetah is not meant as a
50 replacement for properly structured class hierarchies (which
51 Cheetah supports). That said if you are building a web application
52 `@staticmethod <http://docs.python.org/library/functions.html#staticmethod>`_/`@classmethod <http://docs.python.org/library/functions.html#classmethod>`_ are quite useful for the little snippets
53 of markup, etc that are needed (Google AdSense blocks, footers,
54 banners, etc).