"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "docs/users_guide/tipsAndTricks.rst" between
cheetah3-3.1.0.tar.gz and cheetah3-3.2.0.tar.gz

About: Cheetah3 is a template engine and code generation tool for e.g. for Web development or Java, SQL, LaTeX, form email ... (written in Python).

tipsAndTricks.rst  (cheetah3-3.1.0):tipsAndTricks.rst  (cheetah3-3.2.0)
Tips, Tricks and Troubleshooting Tips, Tricks and Troubleshooting
================================ ================================
(tips)
This chapter contains short stuff that doesn't fit anywhere else. This chapter contains short stuff that doesn't fit anywhere else.
See the Cheetah FAQ for more specialized issues and for See the Cheetah FAQ for more specialized issues and for
troubleshooting tips. Check the wiki periodically for recent tips troubleshooting tips. Check the wiki periodically for recent tips
contributed by users. If you get stuck and none of these resources contributed by users. If you get stuck and none of these resources
help, ask on the mailing list. help, ask on the mailing list.
Placeholder Tips Placeholder Tips
---------------- ----------------
(tips.placeholder)
Here's how to do certain important lookups that may not be obvious. Here's how to do certain important lookups that may not be obvious.
For each, we show first the Cheetah expression and then the Python For each, we show first the Cheetah expression and then the Python
equivalent, because you can use these either in templates or in equivalent, because you can use these either in templates or in
pure Python subclasses. The Cheetah examples use NameMapper pure Python subclasses. The Cheetah examples use NameMapper
shortcuts (uniform dotted notation, autocalling) as much as shortcuts (uniform dotted notation, autocalling) as much as
possible. possible.
To verify whether a variable exists in the searchList: To verify whether a variable exists in the searchList:
:: ::
skipping to change at line 82 skipping to change at line 78
didn't expect, screwing up your program. To avoid all this, know didn't expect, screwing up your program. To avoid all this, know
what your namespaces contain, and place the namespaces you have the what your namespaces contain, and place the namespaces you have the
most control over first. For namespaces that could contain most control over first. For namespaces that could contain
user-supplied "other" variables, don't put the namespace itself in user-supplied "other" variables, don't put the namespace itself in
the searchList; instead, copy the needed variables into your own the searchList; instead, copy the needed variables into your own
"safe" namespace. "safe" namespace.
Diagnostic Output Diagnostic Output
----------------- -----------------
(tips.diagnostic)
If you need send yourself some debugging output, you can use If you need send yourself some debugging output, you can use
{#silent} to output it to standard error: {#silent} to output it to standard error:
:: ::
#silent $sys.stderr.write("Incorrigible var is '$incorrigible'.\n") #silent $sys.stderr.write("Incorrigible var is '$incorrigible'.\n")
#silent $sys.stderr.write("Is 'unknown' in the searchList? " + #silent $sys.stderr.write("Is 'unknown' in the searchList? " +
$getVar("unknown", "No.") + "\n" ) $getVar("unknown", "No.") + "\n" )
(Tip contributed by Greg Czajkowski.)
When to use Python methods When to use Python methods
-------------------------- --------------------------
(tips.pythonMethods)
You always have a choice whether to code your methods as Cheetah You always have a choice whether to code your methods as Cheetah
{#def} methods or Python methods (the Python methods being located {#def} methods or Python methods (the Python methods being located
in a class your template inherits). So how do you choose? in a class your template inherits). So how do you choose?
Generally, if the method consists mostly of text and placeholders, Generally, if the method consists mostly of text and placeholders,
use a Cheetah method (a {#def} method). That's why {#def} exists, use a Cheetah method (a {#def} method). That's why {#def} exists,
to take the tedium out of writing those kinds of methods. And if to take the tedium out of writing those kinds of methods. And if
you have a couple {#if} stanzas to {#set} some variables, followed you have a couple {#if} stanzas to {#set} some variables, followed
by a {#for} loop, no big deal. But if your method consists mostly by a {#for} loop, no big deal. But if your method consists mostly
of directives and only a little text, you're better off writing it of directives and only a little text, you're better off writing it
skipping to change at line 142 skipping to change at line 132
one method call the other. Usually this means the Cheetah method one method call the other. Usually this means the Cheetah method
calling the Python method to calculate the needed values, then the calling the Python method to calculate the needed values, then the
Cheetah method produces the output. One snag you might run into Cheetah method produces the output. One snag you might run into
though is that {#set} currently can set only one variable per though is that {#set} currently can set only one variable per
statement, so if your Python method needs to return multiple values statement, so if your Python method needs to return multiple values
to your Cheetah method, you'll have to do it another way. to your Cheetah method, you'll have to do it another way.
Calling superclass methods, and why you have to Calling superclass methods, and why you have to
----------------------------------------------- -----------------------------------------------
(tips.callingSuperclassMethods)
If your template or pure Python class overrides a standard method If your template or pure Python class overrides a standard method
or attribute of {Template} or one of its base classes, you should or attribute of {Template} or one of its base classes, you should
call the superclass method in your method to prevent various things call the superclass method in your method to prevent various things
from breaking. The most common methods to override are {.awake} and from breaking. The most common methods to override are {.awake} and
{.\_\_init\_\_}. {.awake} is called automatically by Webware early {.\_\_init\_\_}. {.awake} is called automatically by Webware early
during the web transaction, so it makes a convenient place to put during the web transaction, so it makes a convenient place to put
Python initialization code your template needs. You'll definitely Python initialization code your template needs. You'll definitely
want to call the superclass {.awake} because it sets up many want to call the superclass {.awake} because it sets up many
wonderful attributes and methods, such as those to access the CGI wonderful attributes and methods, such as those to access the CGI
input fields. input fields.
skipping to change at line 210 skipping to change at line 198
class MyMixin: class MyMixin:
def awake(self, trans): def awake(self, trans):
args = (trans,) args = (trans,)
callbase(self, MyMixin, 'awake', args) callbase(self, MyMixin, 'awake', args)
... everything else you want to do ... ... everything else you want to do ...
=========================================================================== ===========================================================================
All methods All methods
----------- -----------
(tips.allMethods)
Here is a list of all the standard methods and attributes that can Here is a list of all the standard methods and attributes that can
be accessed from a placeholder. Some of them exist for you to call, be accessed from a placeholder. Some of them exist for you to call,
others are mainly used by Cheetah internally but you can call them others are mainly used by Cheetah internally but you can call them
if you wish, and others are only for internal use by Cheetah or if you wish, and others are only for internal use by Cheetah or
Webware. Do not use these method names in mixin classes Webware. Do not use these method names in mixin classes
({#extends}, section inheritanceEtc.extends) unless you intend to ({#extends}, section inheritanceEtc.extends) unless you intend to
override the standard method. override the standard method.
Variables with a star prefix ({ \*}) are frequently used in Variables with a star prefix ({ \*}) are frequently used in
templates or in pure Python classes. templates or in pure Python classes.
skipping to change at line 387 skipping to change at line 373
True if the servlet can be multithreaded. True if the servlet can be multithreaded.
True if the servlet can be used for another transaction after the True if the servlet can be used for another transaction after the
current transaction is finished. current transaction is finished.
Depreciated by {.serverSidePath()}. Depreciated by {.serverSidePath()}.
Optimizing templates Optimizing templates
-------------------- --------------------
(tips.optimizing)
Here are some things you can do to make your templates fill faster Here are some things you can do to make your templates fill faster
and user fewer CPU cycles. Before you put a lot of energy into and user fewer CPU cycles. Before you put a lot of energy into
this, however, make sure you really need to. In many situations, this, however, make sure you really need to. In many situations,
templates appear to initialize and fill instantaneously, so no templates appear to initialize and fill instantaneously, so no
optimization is necessary. If you do find a situation where your optimization is necessary. If you do find a situation where your
templates are filling slowly or taking too much memory or too many templates are filling slowly or taking too much memory or too many
CPU cycles, we'd like to hear about it on the mailing list. CPU cycles, we'd like to hear about it on the mailing list.
Cache $placeholders whose values don't change frequently. (Section Cache $placeholders whose values don't change frequently. (Section
output.caching). output.caching).
skipping to change at line 428 skipping to change at line 412
:: ::
#silent $myMethod($arg1, $arg2, $arg3) #silent $myMethod($arg1, $arg2, $arg3)
Otherwise you'd have to call {self.getVar('arg1')} etc in your Otherwise you'd have to call {self.getVar('arg1')} etc in your
method, which is more wordy, and tedious. method, which is more wordy, and tedious.
PSP-style tags PSP-style tags
-------------- --------------
(tips.PSP)
{<%= ... %>} and {<% ... %>} allow an escape to Python syntax {<%= ... %>} and {<% ... %>} allow an escape to Python syntax
inside the template. You do not need it to use Cheetah effectively, inside the template. You do not need it to use Cheetah effectively,
and we're hard pressed to think of a case to recommend it. and we're hard pressed to think of a case to recommend it.
Nevertheless, it's there in case you encounter a situation you Nevertheless, it's there in case you encounter a situation you
can't express adequately in Cheetah syntax. For instance, to set a can't express adequately in Cheetah syntax. For instance, to set a
local variable to an elaborate initializer. local variable to an elaborate initializer.
{<%= ... %>} encloses a Python expression whose result will be {<%= ... %>} encloses a Python expression whose result will be
printed in the output. printed in the output.
skipping to change at line 465 skipping to change at line 447
<% break %> ## Wrong! <% break %> ## Wrong!
you'll get a {SyntaxError} when you fill the template, but that's you'll get a {SyntaxError} when you fill the template, but that's
what you deserve. what you deserve.
Note that these are PSP-{ style} tags, not PSP tags. A Cheetah Note that these are PSP-{ style} tags, not PSP tags. A Cheetah
template is not a PSP document, and you can't use PSP commands in template is not a PSP document, and you can't use PSP commands in
it. it.
Calling one template from another
---------------------------------
Cheetah templates are really python modules in disguise. I.e., when
Cheetah loads a template it compiles it to python code and then to byte
code. Every template is compiled as a single class. The thing is,
neither the source code nor byte code are saved to files automatically.
There are a few ways to allow a user to import one template (python
module!) from another.
1. A user can compile templates to `*.py` files using `cheetah compile`
command line program. Then import works at the Python level.
To semi-automatically compile all templates after editing them one can
use the following `Makefile` (GNU flavour)::
.SUFFIXES: # Clear the suffix list
.SUFFIXES: .py .tmpl
%.py: %.tmpl
cheetah compile --nobackup $<
python -m compile $@
templates = $(shell echo \*.tmpl)
modules = $(patsubst %.tmpl,%.py,$(templates))
.PHONY: all
all: $(modules)
(Don't forget - makefiles require indent with tabs, not spaces.)
2. Subvert Python import to make Cheetah import directly from `*.tmpl`
files using `import hooks <../api/Cheetah.ImportHooks.html>`_.
Example code::
from Cheetah import ImportHooks
ImportHooks.install()
import sys
sys.path.insert(0, 'path/to/template_dir') # or sys.path.append
ImportHooks try to import from `*.pyc`, `*.py` and `*.tmpl` - whatever
is found first. ImportHooks automatically compile `*.tmpl` to `*.py` and
`*.pyc`.
Makefiles Makefiles
--------- ---------
(tips.Makefile)
If your project has several templates and you get sick of typing If your project has several templates and you get sick of typing
"cheetah compile FILENAME.tmpl" all the time-much less remembering "cheetah compile FILENAME.tmpl" all the time-much less remembering
which commands to type when-and your system has the {make} command which commands to type when-and your system has the {make} command
available, consider building a Makefile to make your life easier. available, consider building a Makefile to make your life easier.
Here's a simple Makefile that controls two templates, Here's a simple Makefile that controls two templates,
ErrorsTemplate and InquiryTemplate. Two external commands, ErrorsTemplate and InquiryTemplate. Two external commands,
{inquiry} and {receive}, depend on ErrorsTemplate.py. Aditionally, {inquiry} and {receive}, depend on ErrorsTemplate.py. Aditionally,
InquiryTemplate itself depends on ErrorsTemplate. InquiryTemplate itself depends on ErrorsTemplate.
skipping to change at line 512 skipping to change at line 539
{make receive}. Or you can recompile only ErrorsTemplate by typing {make receive}. Or you can recompile only ErrorsTemplate by typing
{make ErrorsTemplate}. There's also another target, "printsource": {make ErrorsTemplate}. There's also another target, "printsource":
this sends a Postscript version of the project's source files to this sends a Postscript version of the project's source files to
the printer. The .PHONY target is explained in the {make} the printer. The .PHONY target is explained in the {make}
documentation; essentially, you have it depend on every target that documentation; essentially, you have it depend on every target that
doesn't produce an output file with the same name as the target. doesn't produce an output file with the same name as the target.
Using Cheetah in a Multi-Threaded Application Using Cheetah in a Multi-Threaded Application
--------------------------------------------- ---------------------------------------------
(tips.threads)
Template classes may be shared freely between threads. However, Template classes may be shared freely between threads. However,
template instances should not be shared unless you either: template instances should not be shared unless you either:
- Use a lock (mutex) to serialize template fills, to prevent two - Use a lock (mutex) to serialize template fills, to prevent two
threads from filling the template at the same time. threads from filling the template at the same time.
- Avoid thread-unsafe features: - Avoid thread-unsafe features:
- Modifying searchList values or instance variables. - Modifying searchList values or instance variables.
skipping to change at line 556 skipping to change at line 581
complete. complete.
For Webware servlets, you're probably better off using Webware's For Webware servlets, you're probably better off using Webware's
servlet caching rather than Cheetah's caching. Don't override the servlet caching rather than Cheetah's caching. Don't override the
servlet's {.canBeThreaded()} method unless you avoid the unsafe servlet's {.canBeThreaded()} method unless you avoid the unsafe
operations listed above. operations listed above.
Using Cheetah with gettext Using Cheetah with gettext
-------------------------- --------------------------
(tips.gettext)
{ gettext} is a project for creating internationalized { gettext} is a project for creating internationalized
applications. For more details, visit applications. For more details, visit
http://docs.python.org/lib/module-gettext.html. gettext can be used http://docs.python.org/lib/module-gettext.html. gettext can be used
with Cheetah to create internationalized applications, even for CJK with Cheetah to create internationalized applications, even for CJK
character sets, but you must keep a couple things in mind: character sets, but you must keep a couple things in mind:
- xgettext is used on compiled templates, not on the templates - xgettext is used on compiled templates, not on the templates
themselves. themselves.
- The way the NameMapper syntax gets compiled to Python gets in - The way the NameMapper syntax gets compiled to Python gets in
 End of changes. 13 change blocks. 
24 lines changed or deleted 47 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)