Debian Codegraph @

docs/users_guide/comparisons.rst

raw
1 Cheetah vs. Other Template Engines
2 ==================================
3
4
5 This appendix compares Cheetah with various other template/emdedded
6 scripting languages and Internet development frameworks. As Cheetah
7 is similar to Velocity at a superficial level, you may also wish to
8 read comparisons between Velocity and other languages at
9 http://jakarta.apache.org/velocity/ymtd/ymtd.html.
10
11 Which features are unique to Cheetah
12 ------------------------------------
13
14
15
16 - The { block framework} (section inheritanceEtc.block)
17
18 - Cheetah's powerful yet simple { caching framework} (section
19 output.caching)
20
21 - Cheetah's { Unified Dotted Notation} and { autocalling}
22 (sections language.namemapper.dict and
23 language.namemapper.autocalling)
24
25 - Cheetah's searchList (section language.searchList) information.
26
27 - Cheetah's {#raw} directive (section output.raw)
28
29 - Cheetah's {#slurp} directive (section output.slurp)
30
31 - Cheetah's tight integration with Webware for Python (section
32 webware)
33
34 - Cheetah's { SkeletonPage framework} (section
35 libraries.templates.skeletonPage)
36
37 - Cheetah's ability to mix PSP-style code with Cheetah Language
38 syntax (section tips.PSP) Because of Cheetah's design and Python's
39 flexibility it is relatively easy to extend Cheetah's syntax with
40 syntax elements from almost any other template or embedded
41 scripting language.
42
43
44 Cheetah vs. Velocity
45 --------------------
46
47
48 For a basic introduction to Velocity, visit
49 http://jakarta.apache.org/velocity.
50
51 Velocity is a Java template engine. It's older than Cheetah, has a
52 larger user base, and has better examples and docs at the moment.
53 Cheetah, however, has a number of advantages over Velocity:
54
55
56 - Cheetah is written in Python. Thus, it's easier to use and
57 extend.
58
59 - Cheetah's syntax is closer to Python's syntax than Velocity's is
60 to Java's.
61
62 - Cheetah has a powerful caching mechanism. Velocity has no
63 equivalent.
64
65 - It's far easier to add data/objects into the namespace where
66 $placeholder values are extracted from in Cheetah. Velocity calls
67 this namespace a 'context'. Contexts are dictionaries/hashtables.
68 You can put anything you want into a context, BUT you have to use
69 the .put() method to populate the context; e.g.,
70
71 ::
72
73 VelocityContext context1 = new VelocityContext();
74 context1.put("name","Velocity");
75 context1.put("project", "Jakarta");
76 context1.put("duplicate", "I am in context1");
77
78 Cheetah takes a different approach. Rather than require you to
79 manually populate the 'namespace' like Velocity, Cheetah will
80 accept any existing Python object or dictionary AS the 'namespace'.
81 Furthermore, Cheetah allows you to specify a list namespaces that
82 will be searched in sequence to find a varname-to-value mapping.
83 This searchList can be extended at run-time.
84
85 If you add a 'foo' object to the searchList and the 'foo' has an
86 attribute called 'bar', you can simply type {$bar} in the template.
87 If the second item in the searchList is dictionary 'foofoo'
88 containing {{'spam':1234, 'parrot':666}}, Cheetah will first look
89 in the 'foo' object for a 'spam' attribute. Not finding it, Cheetah
90 will then go to 'foofoo' (the second element in the searchList) and
91 look among its dictionary keys for 'spam'. Finding it, Cheetah will
92 select {foofoo['spam']} as {$spam}'s value.
93
94 - In Cheetah, the tokens that are used to signal the start of
95 $placeholders and #directives are configurable. You can set them to
96 any character sequences, not just $ and #.
97
98
99 Cheetah vs. WebMacro
100 --------------------
101
102
103 For a basic introduction to WebMacro, visit http://webmacro.org.
104
105 The points discussed in section comparisons.velocity also apply to
106 the comparison between Cheetah and WebMacro. For further
107 differences please refer to
108 http://jakarta.apache.org/velocity/differences.html.
109
110 Cheetah vs. Zope's DTML
111 -----------------------
112
113
114 For a basic introduction to DTML, visit
115 http://www.zope.org/Members/michel/ZB/DTML.dtml.
116
117
118 - Cheetah is faster than DTML.
119
120 - Cheetah does not use HTML-style tags; DTML does. Thus, Cheetah
121 tags are visible in rendered HTML output if something goes wrong.
122
123 - DTML can only be used with ZOPE for web development; Cheetah can
124 be used as a standalone tool for any purpose.
125
126 - Cheetah's documentation is more complete than DTML's.
127
128 - Cheetah's learning curve is shorter than DTML's.
129
130 - DTML has no equivalent of Cheetah's blocks, caching framework,
131 unified dotted notation, and {#raw} directive.
132
133
134 Here are some examples of syntax differences between DTML and
135 Cheetah:
136
137 ::
138
139 <ul>
140 <dtml-in frogQuery>
141 <li><dtml-var animal_name></li>
142 </dtml-in>
143 </ul>
144
145 ::
146
147 <ul>
148 #for $animal_name in $frogQuery
149 <li>$animal_name</li>
150 #end for
151 </ul>
152
153 ::
154
155 <dtml-if expr="monkeys > monkey_limit">
156 <p>There are too many monkeys!</p>
157 <dtml-elif expr="monkeys < minimum_monkeys">
158 <p>There aren't enough monkeys!</p>
159 <dtml-else>
160 <p>There are just enough monkeys.</p>
161 </dtml-if>
162
163 ::
164
165 #if $monkeys > $monkey_limit
166 <p>There are too many monkeys!</p>
167 #else if $monkeys < $minimum_monkeys
168 <p>There aren't enough monkeys!</p>
169 #else
170 <p>There are just enough monkeys.</p>
171 #end if
172
173 ::
174
175 <table>
176 <dtml-in expr="objectValues('File')">
177 <dtml-if sequence-even>
178 <tr bgcolor="grey">
179 <dtml-else>
180 <tr>
181 </dtml-if>
182 <td>
183 <a href="&dtml-absolute_url;"><dtml-var title_or_id></a>
184 </td></tr>
185 </dtml-in>
186 </table>
187
188 ::
189
190 <table>
191 #set $evenRow = 0
192 #for $file in $files('File')
193 #if $evenRow
194 <tr bgcolor="grey">
195 #set $evenRow = 0
196 #else
197 <tr>
198 #set $evenRow = 1
199 #end if
200 <td>
201 <a href="$file.absolute_url">$file.title_or_id</a>
202 </td></tr>
203 #end for
204 </table>
205
206 The last example changed the name of {$objectValues} to {$files}
207 because that's what a Cheetah developer would write. The developer
208 would be responsible for ensuring {$files} returned a list (or
209 tuple) of objects (or dictionaries) containing the attributes (or
210 methods or dictionary keys) 'absolute\_url' and 'title\_or\_id'.
211 All these names ('objectValues', 'absolute\_url' and
212 'title\_or\_id') are standard parts of Zope, but in Cheetah the
213 developer is in charge of writing them and giving them a reasonable
214 behaviour.
215
216 Some of DTML's features are being ported to Cheetah, such as
217 {Cheetah.Tools.MondoReport}, which is based on the {<dtml-in>} tag.
218 We are also planning an output filter as flexible as the
219 {<dtml-var>} formatting options. However, neither of these are
220 complete yet.
221
222 Cheetah vs. Zope Page Templates
223 -------------------------------
224
225
226 For a basic introduction to Zope Page Templates, please visit
227 http://www.zope.org/Documentation/Articles/ZPT2.
228
229 Cheetah vs. PHP's Smarty templates
230 ----------------------------------
231
232
233 PHP (http://www.php.net/) is one of the few scripting languages
234 expressly designed for web servlets. However, it's also a
235 full-fledged programming language with libraries similar to
236 Python's and Perl's. The syntax and functions are like a cross
237 between Perl and C plus some original ideas (e.g.; a single array
238 type serves as both a list and a dictionary, ``$arr[]="value";``
239 appends to an array).
240
241 Smarty (http://smarty.php.net/) is an advanced template engine for
242 PHP. ({ Note:} this comparision is based on Smarty's on-line
243 documentation. The author has not used Smarty. Please send
244 corrections or ommissions to the Cheetah mailing list.) Like
245 Cheetah, Smarty:
246
247
248 - compiles to the target programming language (PHP).
249
250 - has configurable delimeters.
251
252 - passes if-blocks directly to PHP, so you can use any PHP
253 expression in them.
254
255 - allows you to embed PHP code in a template.
256
257 - has a caching framework (although it works quite differently).
258
259 - can read the template definition from any arbitrary source.
260
261
262 Features Smarty has that Cheetah lacks:
263
264
265 - Preprocessors, postprocessors and output filters. You can
266 emulate a preprocessor in Cheetah by running your template
267 definition through a filter program or function before Cheetah sees
268 it. To emulate a postprocessor, run a .py template module through a
269 filter program/function. To emulate a Smarty output filter, run the
270 template output through a filter program/function. If you want to
271 use "cheetah compile" or "cheetah fill" in a pipeline, use {-} as
272 the input file name and {-stdout} to send the result to standard
273 output. Note that Cheetah uses the term "output filter" differently
274 than Smarty: Cheetah output filters ({#filter}) operate on
275 placeholders, while Smarty output filters operate on the entire
276 template output. There has been a proposed {#sed} directive that
277 would operate on the entire output line by line, but it has not
278 been implemented.
279
280 - Variable modifiers. In some cases, Python has equivalent string
281 methods ({.strip}, {.capitalize}, {.replace(SEARCH, REPL)}), but in
282 other cases you must wrap the result in a function call or write a
283 custom output filter ({#filter}).
284
285 - Certain web-specific functions, which can be emulated with
286 third-party functions.
287
288 - The ability to "plug in" new directives in a modular way.
289 Cheetah directives are tightly bound to the compiler. However,
290 third-party { functions} can be freely imported and called from
291 placeholders, and { methods} can be mixed in via {#extends}. Part
292 of this is because Cheetah distinguishes between functions and
293 directives, while Smarty treats them all as "functions". Cheetah's
294 design does not allow functions to have flow control effect outside
295 the function (e.g., {#if} and {#for}, which operate on template
296 body lines), so directives like these cannot be encoded as
297 functions.
298
299 - Configuration variables read from an .ini-style file. The
300 {Cheetah.SettingsManager} module can parse such a file, but you'd
301 have to invoke it manually. (See the docstrings in the module for
302 details.) In Smarty, this feature is used for multilingual
303 applications. In Cheetah, the developers maintain that everybody
304 has their own preferred way to do this (such as using Python's
305 {gettext} module), and it's not worth blessing one particular
306 strategy in Cheetah since it's easy enough to integrate third-party
307 code around the template, or to add the resulting values to the
308 searchList.
309
310
311 Features Cheetah has that Smarty lacks:
312
313
314 - Saving the compilation result in a Python (PHP) module for quick
315 reading later.
316
317 - Caching individual placeholders or portions of a template.
318 Smarty caches only the entire template output as a unit.
319
320
321 Comparisions of various Smarty constructs:
322
323 ::
324
325 {assign var="name" value="Bob"} (#set has better syntax in the author's opinion)
326 counter (looks like equivalent to #for)
327 eval (same as #include with variable)
328 fetch: insert file content into output (#include raw)
329 fetch: insert URL content into output (no euqivalent, user can write
330 function calling urllib, call as $fetchURL('URL') )
331 fetch: read file into variable (no equivalent, user can write function
332 based on the 'open/file' builtin, or on .getFileContents() in
333 Template.)
334 fetch: read URL content into variable (no equivalent, use above
335 function and call as: #set $var = $fetchURL('URL')
336 html_options: output an HTML option list (no equivalent, user can
337 write custom function. Maybe FunFormKit can help.)
338 html_select_date: output three dropdown controls to specify a date
339 (no equivalent, user can write custom function)
340 html_select_time: output four dropdown controls to specify a time
341 (no equvalent, user can write custom function)
342 math: eval calculation and output result (same as #echo)
343 math: eval calculation and assign to variable (same as #set)
344 popup_init: library for popup windows (no equivalent, user can write
345 custom method outputting Javascript)
346
347
348 Other commands:
349 capture (no equivalent, collects output into variable. A Python
350 program would create a StringIO instance, set sys.stdout to
351 it temporarily, print the output, set sys.stdout back, then use
352 .getvalue() to get the result.)
353 config_load (roughly analagous to #settings, which was removed
354 from Cheetah. Use Cheetah.SettingsManager manually or write
355 a custom function.)
356 include (same as #include, but can include into variable.
357 Variables are apparently shared between parent and child.)
358 include_php: include a PHP script (e.g., functions)
359 (use #extends or #import instead)
360 insert (same as #include not in a #cache region)
361 {ldelim}{rdelim} (escape literal $ and # with a backslash,
362 use #compiler-settings to change the delimeters)
363 literal (#raw)
364 php (``<% %>'' tags)
365 section (#for $i in $range(...) )
366 foreach (#for)
367 strip (like the #sed tag which was never implemented. Strips
368 leading/trailing whitespace from lines, joins several lines
369 together.)
370
371
372 Variable modifiers:
373 capitalize ( $STRING.capitalize() )
374 count_characters ( $len(STRING) )
375 count_paragraphs/sentances/words (no equivalent, user can write function)
376 date_format (use 'time' module or download Egenix's mx.DateTime)
377 default ($getVar('varName', 'default value') )
378 escape: html encode ($cgi.escape(VALUE) )
379 escape: url encode ($urllib.quote_plus(VALUE) )
380 escape: hex encode (no equivalent? user can write function)
381 escape: hex entity encode (no equivalent? user can write function)
382 indent: indent all lines of a var's output (may be part of future
383 #indent directive)
384 lower ($STRING.lower() )
385 regex_replace ('re' module)
386 replace ($STRING.replace(OLD, NEW, MAXSPLIT) )
387 spacify (#echo "SEPARATOR".join(SEQUENCE) )
388 string_format (#echo "%.2f" % FLOAT , etc.)
389 strip_tags (no equivalent, user can write function to strip HTML tags,
390 or customize the WebSafe filter)
391 truncate (no equivalent, user can write function)
392 upper ($STRING.upper() )
393 wordwrap ('writer' module, or a new module coming in Python 2.3)
394
395 Some of these modifiers could be added to the super output filter
396 we want to write someday.
397
398 Cheetah vs. PHPLib's Template class
399 -----------------------------------
400
401
402 PHPLib ((http://phplib.netuse.de/) is a collection of classes for
403 various web objects (authentication, shopping cart, sessions, etc),
404 but what we're interested in is the {Template} object. It's much
405 more primitive than Smarty, and was based on an old Perl template
406 class. In fact, one of the precursors to Cheetah was based on it
407 too. Differences from Cheetah:
408
409
410 - Templates consist of text with {{placeholders}} in braces.
411
412 - Instead of a searchList, there is one flat namespace. Every
413 variable must be assigned via the {set\_var} method. However, you
414 can pass this method an array (dictionary) of several variables at
415 once.
416
417 - You cannot embed lookups or calculations into the template.
418 Every placeholder must be an exact variable name.
419
420 - There are no directives. You must do all display logic (if, for,
421 etc) in the calling routine.
422
423 - There is, however, a "block" construct. A block is a portion of
424 text between the comment markers {<!- BEGIN blockName -> ... <!-
425 END blockName>}. The {set\_block} method extracts this text into a
426 namespace variable and puts a placeholder referring to it in the
427 template. This has a few parallels with Cheetah's {#block}
428 directive but is overall quite different.
429
430 - To do the equivalent of {#if}, extract the block. Then if true,
431 do nothing. If false, assign the empty string to the namespace
432 variable.
433
434 - To do the equivalent of {#for}, extract the block. Set any
435 namespace variables needed inside the loop. To parse one iteration,
436 use the {parse} method to fill the block variable (a mini-template)
437 into another namespace variable, appending to it. Refresh the
438 namespace variables needed inside the loop and parse again; repeat
439 for each iteration. You'll end up with a mini-result that will be
440 plugged into the main template's placeholder.
441
442 - To read a template definition from a file, use the {set\_file}
443 method. This places the file's content in a namespace variable. To
444 read a template definition from a string, assign it to a namespace
445 variable.
446
447 - Thus, for complicated templates, you are doing a lot of
448 recursive block filling and file reading and parsing mini-templates
449 all into one flat namespace as you finally build up values for the
450 main template. In Cheetah, all this display logic can be embedded
451 into the template using directives, calling out to Python methods
452 for the more complicated tasks.
453
454 - Although you can nest blocks in the template, it becomes tedious
455 and arguably hard to read, because all blocks have identical
456 syntax. Unless you choose your block names carefully and put
457 comments around them, it's hard to tell which blocks are if-blocks
458 and which are for-blocks, or what their nesting order is.
459
460 - PHPLib templates do not have caching, output filters, etc.
461
462
463 Cheetah vs. PSP, PHP, ASP, JSP, Embperl, etc.
464 ---------------------------------------------
465
466
467 Webware's PSP Component
468 - http://webware.sourceforge.net/Webware/PSP/Docs/
469
470 Tomcat JSP Information
471 - http://jakarta.apache.org/tomcat/index.html
472
473 ASP Information at ASP101
474 - http://www.asp101.com/
475
476 Embperl
477 - http://perl.apache.org/embperl/
478
479
480 Here's a basic Cheetah example:
481
482 ::
483
484 <TABLE>
485 #for $client in $service.clients
486 <TR>
487 <TD>$client.surname, $client.firstname</TD>
488 <TD><A HREF="mailto:$client.email" >$client.email</A></TD>
489 </TR>
490 #end for
491 </TABLE>
492
493 Compare this with PSP:
494
495 ::
496
497 <TABLE>
498 <% for client in service.clients(): %>
499 <TR>
500 <TD><%=client.surname()%>, <%=client.firstname()%></TD>
501 <TD><A HREF="mailto:<%=client.email()%>"><%=client.email()%></A></TD>
502 </TR>
503 <%end%>
504 </TABLE>
505
506