summaryrefslogtreecommitdiff
path: root/docs/html/users_guide/language.html
blob: dbb5d91ba9582c5bf7321975a904d8ac69d3ef66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Language Overview &#8212; Cheetah3 - The Python-Powered Template Engine</title>
    <link rel="stylesheet" href="../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.1.0',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Comments" href="comments.html" />
    <link rel="prev" title="Getting Started" href="gettingStarted.html" /> 
  </head>
  <body>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="comments.html" title="Comments"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gettingStarted.html" title="Getting Started"
             accesskey="P">previous</a> |</li>
        <li class="nav-item nav-item-0"><a href="../index.html">Cheetah3 - The Python-Powered Template Engine</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Cheetah User’s Guide</a> &#187;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../index.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Language Overview</a><ul>
<li><a class="reference internal" href="#language-constructs-summary">Language Constructs - Summary</a></li>
<li><a class="reference internal" href="#placeholder-syntax-rules">Placeholder Syntax Rules</a></li>
<li><a class="reference internal" href="#where-can-you-use-placeholders">Where can you use placeholders?</a></li>
<li><a class="reference internal" href="#are-all-those-dollar-signs-really-necessary">Are all those dollar signs really necessary?</a></li>
<li><a class="reference internal" href="#namemapper-syntax">NameMapper Syntax</a><ul>
<li><a class="reference internal" href="#example">Example</a></li>
<li><a class="reference internal" href="#dictionary-access">Dictionary Access</a></li>
<li><a class="reference internal" href="#autocalling">Autocalling</a></li>
</ul>
</li>
<li><a class="reference internal" href="#namespace-cascading-and-the-searchlist">Namespace cascading and the searchList</a></li>
<li><a class="reference internal" href="#missing-values">Missing Values</a></li>
<li><a class="reference internal" href="#directive-syntax-rules">Directive Syntax Rules</a><ul>
<li><a class="reference internal" href="#directive-closures-and-whitespace-handling">Directive closures and whitespace handling</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gettingStarted.html"
                        title="previous chapter">Getting Started</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="comments.html"
                        title="next chapter">Comments</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/users_guide/language.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="language-overview">
<h1>Language Overview<a class="headerlink" href="#language-overview" title="Permalink to this headline">¶</a></h1>
<p>(language)</p>
<p>Cheetah’s basic syntax was inspired by the Java-based template
engines Velocity and WebMacro. It has two types of tags: {
$placeholders} and { #directives}. Both types are case-sensitive.</p>
<p>Placeholder tags begin with a dollar sign ({$varName}) and are
similar to data fields in a form letter or to the {%(key)s} fields
on the left side of Python’s {%} operator. When the template is
filled, the placeholders are replaced with the values they refer
to.</p>
<p>Directive tags begin with a hash character (#) and are used for
comments, loops, conditional blocks, includes, and all other
advanced features. ({ Note:} you can customize the start and end
delimeters for placeholder and directive tags, but in this Guide
we’ll assume you’re using the default.)</p>
<p>Placeholders and directives can be escaped by putting a backslash
before them. <code class="docutils literal"><span class="pre">\$var</span></code> and <code class="docutils literal"><span class="pre">\#if</span></code> will be output as literal
text.</p>
<p>A placeholder or directive can span multiple physical lines,
following the same rules as Python source code: put a backslash
(<code class="docutils literal"><span class="pre">\</span></code>) at the end of all lines except the last line. However, if
there’s an unclosed parenthesis, bracket or brace pending, you
don’t need the backslash.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>#if $this_is_a_very_long_line and $has_lots_of_conditions \
    and $more_conditions:
&lt;H1&gt;bla&lt;/H1&gt;
#end if

#if $country in (&#39;Argentina&#39;, &#39;Uruguay&#39;, &#39;Peru&#39;, &#39;Colombia&#39;,
    &#39;Costa Rica&#39;, &#39;Venezuela&#39;, &#39;Mexico&#39;)
&lt;H1&gt;Hola, senorita!&lt;/H1&gt;
#else
&lt;H1&gt;Hey, baby!&lt;/H1&gt;
#end if
</pre></div>
</div>
<div class="section" id="language-constructs-summary">
<h2>Language Constructs - Summary<a class="headerlink" href="#language-constructs-summary" title="Permalink to this headline">¶</a></h2>
<p>(language.constructs)</p>
<ol class="arabic simple">
<li>Comments and documentation strings<ol class="arabic">
<li>{## single line}</li>
<li>{#* multi line *#}</li>
</ol>
</li>
<li>Generation, caching and filtering of output<ol class="arabic">
<li>plain text</li>
<li>look up a value: {$placeholder}</li>
<li>evaluate an expression: {#echo} …</li>
<li>same but discard the output: {#silent} …</li>
<li>one-line if: {#if EXPR then EXPR else EXPR}</li>
<li>gobble the EOL: {#slurp}</li>
<li>parsed file includes: {#include} …</li>
<li>raw file includes: {#include raw} …</li>
<li>verbatim output of Cheetah code: {#raw} … {#end raw}</li>
<li>cached placeholders: {$*var}, {$*&lt;interval&gt;*var}</li>
<li>cached regions: {#cache} … {#end cache}</li>
<li>set the output filter: {#filter} …</li>
<li>control output indentation: {#indent} … ({ not implemented
yet})</li>
</ol>
</li>
<li>Importing Python modules and objects: {#import} …, {#from}
…</li>
<li>Inheritance<ol class="arabic">
<li>set the base class to inherit from: {#extends}</li>
<li>set the name of the main method to implement: {#implements}
…</li>
</ol>
</li>
<li>Compile-time declaration<ol class="arabic">
<li>define class attributes: {#attr} …</li>
<li>define class methods: {#def} … {#end def}</li>
<li>{#block} … {#end block} provides a simplified interface to
{#def} … {#end def}</li>
</ol>
</li>
<li>Run-time assignment<ol class="arabic">
<li>local vars: {#set} …</li>
<li>global vars: {#set global} …</li>
<li>deleting local vars: {#del} …</li>
</ol>
</li>
<li>Flow control<ol class="arabic">
<li>{#if} … {#else} … {#else if} (aka {#elif}) … {#end if}</li>
<li>{#unless} … {#end unless}</li>
<li>{#for} … {#end for}</li>
<li>{#repeat} … {#end repeat}</li>
<li>{#while} … {#end while}</li>
<li>{#break}</li>
<li>{#continue}</li>
<li>{#pass}</li>
<li>{#stop}</li>
</ol>
</li>
<li>error/exception handling<ol class="arabic">
<li>{#assert}</li>
<li>{#raise}</li>
<li>{#try} … {#except} … {#else} … {#end try}</li>
<li>{#try} … {#finally} … {#end try}</li>
<li>{#errorCatcher} … set a handler for exceptions raised by
$placeholder calls.</li>
</ol>
</li>
<li>Instructions to the parser/compiler<ol class="arabic">
<li>{#breakpoint}</li>
<li>{#compiler-settings} … {#end compiler-settings}</li>
</ol>
</li>
<li>Escape to pure Python code<ol class="arabic">
<li>evalute expression and print the output: {&lt;%=} … {%&gt;}</li>
<li>execute code and discard output: {&lt;%} … {%&gt;}</li>
</ol>
</li>
<li>Fine control over Cheetah-generated Python modules<ol class="arabic">
<li>set the source code encoding of compiled template modules:
{#encoding}</li>
<li>set the sh-bang line of compiled template modules: {#shBang}</li>
</ol>
</li>
</ol>
<p>The use of all these constructs will be covered in the next several
chapters.</p>
</div>
<div class="section" id="placeholder-syntax-rules">
<h2>Placeholder Syntax Rules<a class="headerlink" href="#placeholder-syntax-rules" title="Permalink to this headline">¶</a></h2>
<p>(language.placeholders.syntax)</p>
<ul>
<li><p class="first">Placeholders follow the same syntax rules as Python variables
except that they are preceded by {$} (the short form) or enclosed
in {${}} (the long form). Examples:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$var
${var}
$var2.abc[&#39;def&#39;](&#39;gh&#39;, $subplaceholder, 2)
${var2.abc[&#39;def&#39;](&#39;gh&#39;, $subplaceholder, 2)}
</pre></div>
</div>
<p>We recommend {$} in simple cases, and {${}} when followed directly
by a letter or when Cheetah or a human template maintainer might
get confused about where the placeholder ends. You may alternately
use <code class="docutils literal"><span class="pre">$()</span></code> or <code class="docutils literal"><span class="pre">$[]</span></code>, although this may confuse the (human)
template maintainer:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$(var)
$[var]
$(var2.abc[&#39;def&#39;](&#39;gh&#39;, $subplaceholder, 2))
$[var2.abc[&#39;def&#39;](&#39;gh&#39;, $subplaceholder, 2)]
</pre></div>
</div>
<p>{ Note:} Advanced users can change the delimiters to anything they
want via the {#compiler} directive.</p>
<p>{ Note 2:} The long form can be used only with top-level
placeholders, not in expressions. See section
language.placeholders.positions for an elaboration on this.</p>
</li>
<li><p class="first">To reiterate Python’s rules, placeholders consist of one or more
identifiers separated by periods. Each identifier must start with a
letter or an underscore, and the subsequent characters must be
letters, digits or underscores. Any identifier may be followed by
arguments enclosed in <code class="docutils literal"><span class="pre">()</span></code> and/or keys/subscripts in <code class="docutils literal"><span class="pre">[]</span></code>.</p>
</li>
<li><p class="first">Identifiers are case sensitive. {$var} does not equal {$Var} or
{$vAr} or {$VAR}.</p>
</li>
<li><p class="first">Arguments inside <code class="docutils literal"><span class="pre">()</span></code> or <code class="docutils literal"><span class="pre">[]</span></code> are just like in Python.
Strings may be quoted using any Python quoting style. Each argument
is an expression and may use any of Python’s expression operators.
Variables used in argument expressions are placeholders and should
be prefixed with {$}. This also applies to the *arg and **kw
forms. However, you do { not} need the {$} with the special Python
constants {None}, {True} and {False}. Examples:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$hex($myVar)
$func($arg=1234)
$func2($*args, $**kw)
$func3(3.14159, $arg2, None, True)
$myList[$mySubscript]
</pre></div>
</div>
</li>
<li><p class="first">Trailing periods are ignored. Cheetah will recognize that the
placeholder name in {$varName.} is {varName}, and the period will
be left alone in the template output.</p>
</li>
<li><p class="first">The syntax {${placeholderName, arg1=”val1”}} passes arguments to
the output filter (see {#filter}, section output.filter. The braces
and comma are required in this case. It’s conventional to omit the
{$} before the keyword arguments (i.e. {arg1}) in this case.</p>
</li>
<li><p class="first">Cheetah ignores all dollar signs ({$}) that are not followed by
a letter or an underscore.</p>
</li>
</ul>
<p>The following are valid $placeholders:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$a $_ $var $_var $var1 $_1var $var2_ $dict.key $list[3]
$object.method $object.method() $object.method
$nest($nest($var))
</pre></div>
</div>
<p>These are not $placeholders but are treated as literal text:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$@var $^var $15.50 $$
</pre></div>
</div>
</div>
<div class="section" id="where-can-you-use-placeholders">
<h2>Where can you use placeholders?<a class="headerlink" href="#where-can-you-use-placeholders" title="Permalink to this headline">¶</a></h2>
<p>(language.placeholders.positions)</p>
<p>There are three places you can use placeholders: top-level
position, expression position and LVALUE position. Each has
slightly different syntax rules.</p>
<p>Top-level position means interspersed in text. This is the only
place you can use the placeholder long form: {${var}}.</p>
<p>{ Expression position} means inside a Cheetah expression, which is
the same as a Python expression. The placeholder names a searchList
or other variable to be read. Expression position occurs inside ()
and <span class="math">$[]$</span> arguments within placeholder tags (i.e., a
placeholder inside a placeholder), and in several directive tags.</p>
<p>{ LVALUE position} means naming a variable that will be written to.
LVALUE is a computer science term meaning
“the left side of an assignment statement”. The first argument of
directives {#set}, {#for}, {#def}, {#block} and {#attr} is an
LVALUE.</p>
<p>This stupid example shows the three positions. Top-level position
is shown in {courier}, expression position is { italic}, and LVALUE
position is { bold}.</p>
<blockquote>
<div>#for { $count} in { $range}({ $ninetyNine}, 0, -1)
#set { $after} = { $count} - 1
{$count} bottles of beer on the wall. {$count} bottles of beer!
Take one down, pass it around. {$after} bottles of beer on the
wall.
#end for
{$hex}({ $myVar}, { $default}={ None})</div></blockquote>
<p>The output of course is:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>99 bottles of beer on the wall.  99 bottles of beer!
    Take one down, pass it around.  98 bottles of beer on the wall.
98 bottles of beer on the wall.  98 bottles of beer!
    Take one down, pass it around.  97 bottles of beer on the wall.
...
</pre></div>
</div>
</div>
<div class="section" id="are-all-those-dollar-signs-really-necessary">
<h2>Are all those dollar signs really necessary?<a class="headerlink" href="#are-all-those-dollar-signs-really-necessary" title="Permalink to this headline">¶</a></h2>
<p>(language.placeholders.dollar-signs)</p>
<p>{$} is a “smart variable prefix”. When Cheetah sees {$}, it
determines both the variable’s position and whether it’s a
searchList value or a non-searchList value, and generates the
appropriate Python code.</p>
<p>In top-level position, the {$} is { required}. Otherwise there’s
nothing to distinguish the variable from ordinary text, and the
variable name is output verbatim.</p>
<p>In expression position, the {$} is { required} if the value comes
from the searchList or a “#set global” variable, { recommended} for
local/global/builtin variables, and { not necessary} for the
special constants {None}, {True} and {False}. This works because
Cheetah generates a function call for a searchList placeholder, but
a bare variable name for a local/global/builtin variable.</p>
<p>In LVALUE position, the {$} is { recommended}. Cheetah knows where
an LVALUE is expected, so it can handle your variable name whether
it has {$} or not.</p>
<p>EXCEPTION: Do { not} use the {$} prefix for intermediate variables
in a Python list comprehensions. This is a limitation of Cheetah’s
parser; it can’t tell which variables in a list comprehension are
the intermediate variables, so you have to help it. For example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1">#set $theRange = [x ** 2 for x in $range(10)]</span>
</pre></div>
</div>
<p>{$theRange} is a regular {#set} variable. {$range} is a Python
built-in function. But {x} is a scratch variable internal to the
list comprehension: if you type {$x}, Cheetah will miscompile it.</p>
</div>
<div class="section" id="namemapper-syntax">
<h2>NameMapper Syntax<a class="headerlink" href="#namemapper-syntax" title="Permalink to this headline">¶</a></h2>
<p>(language.namemapper)</p>
<p>One of our core aims for Cheetah was to make it easy for
non-programmers to use. Therefore, Cheetah uses a simplified syntax
for mapping placeholders in Cheetah to values in Python. It’s known
as the { NameMapper syntax} and allows for non-programmers to use
Cheetah without knowing (a) the difference between an instance and
a dictionary, (b) what functions and methods are, and (c) what
‘self’ is. A side benefit is that you can change the underlying
data structure (e.g., instance to dictionary or vice-versa) without
having to modify the templates.</p>
<p>NameMapper syntax is used for all variables in Cheetah placeholders
and directives. If desired, it can be turned off via the {Template}
class’ {‘useNameMapper’} compiler setting. But it’s doubtful you’d
ever want to turn it off.</p>
<div class="section" id="example">
<h3>Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h3>
<p>(language.namemapper.example)</p>
<p>Consider this scenario:</p>
<p>You are building a customer information system. The designers with
you want to use information from your system on the client’s
website -AND- they want to understand the display code and so they
can maintian it themselves.</p>
<p>You write a UI class with a ‘customers’ method that returns a
dictionary of all the customer objects. Each customer object has an
‘address’ method that returns the a dictionary with information
about the customer’s address. The designers want to be able to
access that information.</p>
<p>Using PSP, the display code for the website would look something
like the following, assuming your servlet subclasses the class you
created for managing customer information:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="o">&lt;%=</span> <span class="bp">self</span><span class="o">.</span><span class="n">customer</span><span class="p">()[</span><span class="n">ID</span><span class="p">]</span><span class="o">.</span><span class="n">address</span><span class="p">()[</span><span class="s1">&#39;city&#39;</span><span class="p">]</span> <span class="o">%&gt;</span>   <span class="p">(</span><span class="mi">42</span> <span class="n">chars</span><span class="p">)</span>
</pre></div>
</div>
<p>With Cheetah’s NameMapper syntax, you can use any of the
following:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$self.customers()[$ID].address()[&#39;city&#39;]       (39 chars)
--OR--
$customers()[$ID].address()[&#39;city&#39;]
--OR--
$customers()[$ID].address().city
--OR--
$customers()[$ID].address.city
--OR--
$customers[$ID].address.city                   (27 chars)
</pre></div>
</div>
<p>Which of these would you prefer to explain to the designers, who
have no programming experience? The last form is 15 characters
shorter than the PSP version and - conceptually - far more
accessible. With PHP or ASP, the code would be even messier than
with PSP.</p>
<p>This is a rather extreme example and, of course, you could also
just implement {$getCustomer($ID).city} and obey the Law of Demeter
(search Google for more on that). But good object orientated design
isn’t the point of this example.</p>
</div>
<div class="section" id="dictionary-access">
<h3>Dictionary Access<a class="headerlink" href="#dictionary-access" title="Permalink to this headline">¶</a></h3>
<p>(language.namemapper.dict)</p>
<p>NameMapper syntax allows access to dictionary items with the same
dotted notation used to access object attributes in Python. This
aspect of NameMapper syntax is known as ‘Unified Dotted Notation’.
For example, with Cheetah it is possible to write:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$customers()[&#39;kerr&#39;].address()  --OR--  $customers().kerr.address()
</pre></div>
</div>
<p>where the second form is in NameMapper syntax.</p>
<p>This works only with dictionary keys that also happen to be valid
Python identifiers.</p>
</div>
<div class="section" id="autocalling">
<h3>Autocalling<a class="headerlink" href="#autocalling" title="Permalink to this headline">¶</a></h3>
<p>(language.namemapper.autocalling)</p>
<p>Cheetah automatically detects functions and methods in Cheetah
$variables and calls them if the parentheses have been left off.
Our previous example can be further simplified to:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$customers.kerr.address
</pre></div>
</div>
<p>As another example, if ‘a’ is an object, ‘b’ is a method</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$a.b
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$a.b()
</pre></div>
</div>
<p>If b returns a dictionary, then following variations are possible</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$a.b.c  --OR--  $a.b().c  --OR--  $a.b()[&#39;c&#39;]
</pre></div>
</div>
<p>where ‘c’ is a key in the dictionary that a.b() returns.</p>
<p>Further notes:</p>
<ul class="simple">
<li>When Cheetah autocalls a function/method, it calls it without
any arguments. Thus, the function/method must have been declared
without arguments (except {self} for methods) or to provide default
values for all arguments. If the function requires arguments, you
must use the {()}.</li>
<li>Cheetah autocalls only functions and methods. Classes and other
callable objects are not autocalled. The reason is that the primary
purpose of a function/method is to call it, whereas the primary
purpose of an instance is to look up its attributes or call its
methods, not to call the instance itself. And calling a class may
allocate large sums of memory uselessly or have other side effects,
depending on the class. For instance, consider {$myInstance.fname}.
Do we want to look up {fname} in the namespace of {myInstance} or
in the namespace of whatever {myinstance} returns? It could go
either way, so Cheetah follows the principle of least surprise. If
you { do} want to call the instance, put the {()} on, or rename the
{.__call__()} method to {.__str__}.</li>
<li>Autocalling can be disabled via Cheetah’s ‘useAutocalling’
compiler setting. You can also disable it for one placeholder by
using the syntax {$getVar(‘varName’, ‘default value’, False)}.
({.getVar()} works only with searchList values.)</li>
</ul>
</div>
</div>
<div class="section" id="namespace-cascading-and-the-searchlist">
<h2>Namespace cascading and the searchList<a class="headerlink" href="#namespace-cascading-and-the-searchlist" title="Permalink to this headline">¶</a></h2>
<p>(language.searchList)</p>
<p>When Cheetah maps a variable name in a template to a Python value,
it searches several namespaces in order:</p>
<ol class="arabic simple">
<li>{ Local variables:} created by {#set}, {#for}, or predefined by
Cheetah.</li>
<li>The { searchList}, consisting of:<ol class="arabic">
<li>{#set global} variables.</li>
<li>The { searchList} containers you passed to the {Template}
constructor, if any.</li>
<li>The { Template instance} (“self”). This contains any attributes
you assigned, {#def} methods and {#block methods},
attributes/methods inherited via {#extends}, and other
attributes/methods built into {Template} or inherited by it
(there’s a list of all these methods in section tips.allMethods).</li>
</ol>
</li>
<li>{ Python globals:} created by {#import}, {#from … import}, or
otherwise predefined by Cheetah.</li>
<li>{ Python builtins:} {None}, {max}, etc.</li>
</ol>
<p>The first matching name found is used.</p>
<p>Remember, these namespaces apply only to the { first} identifier
after the {$}. In a placeholder like {$a.b}, only ‘a’ is looked up
in the searchList and other namespaces. ‘b’ is looked up only
inside ‘a’.</p>
<p>A searchList container can be any Python object with attributes or
keys: dictionaries, instances, classes or modules. If an instance
contains both attributes and keys, its attributes are searched
first, then its keys.</p>
<p>Because the {Template} instance is part of the searchList, you can
access its attributes/methods without ‘self’: {$myAttr}. However,
use the ‘self’ if you want to make sure you’re getting the
{Template} attribute and not a same-name variable defined in a
higher namespace: {$self.myAttr}. This works because “self” itself
is a local variable.</p>
<p>The final resulting value, after all lookups and function calls
(but before the filter is applied) is called the { placeholder
value}, no matter which namespace it was found in.</p>
<p>{ { Note carefully:}} if you put an object ‘myObject’ in the
searchList, you { cannot} look up {$myObject}! You can look up only
the attributes/keys { inside} ‘myObject’.</p>
<p>Earlier versions of Cheetah did not allow you to override Python
builtin names, but this was fixed in Cheetah 0.9.15.</p>
<p>If your template will be used as a Webware servlet, do not override
methods ‘name’ and ‘log’ in the {Template} instance or it will
interfere with Webware’s logging. However, it { is} OK to use those
variables in a higher namespace, since Webware doesn’t know about
Cheetah namespaces.</p>
</div>
<div class="section" id="missing-values">
<h2>Missing Values<a class="headerlink" href="#missing-values" title="Permalink to this headline">¶</a></h2>
<p>(language.namemapper.missing)</p>
<p>If NameMapper can not find a Python value for a Cheetah variable
name, it will raise the NameMapper.NotFound exception. You can use
the {#errorCatcher} directive (section errorHandling.errorCatcher)
or { errorCatcher} Template constructor argument (section
howWorks.constructing) to specify an alternate behaviour. BUT BE
AWARE THAT errorCatcher IS ONLY INTENDED FOR DEBUGGING!</p>
<p>To provide a default value for a placeholder, write it like this:
{$getVar(‘varName’, ‘default value’)}. If you don’t specify a
default and the variable is missing, {NameMapper.NotFound} will be
raised.</p>
</div>
<div class="section" id="directive-syntax-rules">
<h2>Directive Syntax Rules<a class="headerlink" href="#directive-syntax-rules" title="Permalink to this headline">¶</a></h2>
<p>(language.directives.syntax)</p>
<p>Directive tags begin with a hash character (#) and are used for
comments, loops, conditional blocks, includes, and all other
advanced features. Cheetah uses a Python-like syntax inside
directive tags and understands any valid Python expression. {
However, unlike Python, Cheetah does not use colons (:) and
indentation to mark off multi-line directives.} That doesn’t work
in an environment where whitespace is significant as part of the
text. Instead, multi-line directives like {#for} have corresponding
closing tags ({#end for}). Most directives are direct mirrors of
Python statements.</p>
<p>Many directives have arguments after the opening tag, which must be
in the specified syntax for the tag. All end tags have the
following syntax:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1">#end TAG_NAME [EXPR]</span>
</pre></div>
</div>
<p>The expression is ignored, so it’s essentially a comment.</p>
<div class="section" id="directive-closures-and-whitespace-handling">
<h3>Directive closures and whitespace handling<a class="headerlink" href="#directive-closures-and-whitespace-handling" title="Permalink to this headline">¶</a></h3>
<p>(language.directives.closures) Directive tags can be closed
explicitly with {#}, or implicitly with the end of the line if
you’re feeling lazy.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1">#block testBlock #</span>
<span class="n">Text</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">body</span> <span class="n">of</span> <span class="n">the</span>
<span class="n">block</span> <span class="n">directive</span>
<span class="c1">#end block testBlock #</span>
</pre></div>
</div>
<p>is identical to:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1">#block testBlock</span>
<span class="n">Text</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">body</span> <span class="n">of</span> <span class="n">the</span>
<span class="n">block</span> <span class="n">directive</span>
<span class="c1">#end block testBlock</span>
</pre></div>
</div>
<p>When a directive tag is closed explicitly, it can be followed with
other text on the same line:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">bah</span><span class="p">,</span> <span class="n">bah</span><span class="p">,</span> <span class="c1">#if $sheep.color == &#39;black&#39;# black#end if # sheep.</span>
</pre></div>
</div>
<p>When a directive tag is closed implicitly with the end of the line,
all trailing whitespace is gobbled, including the newline
character:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo #set $x = 2</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">outputs</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo bar</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="k">while</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo #set $x = 2 #</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">outputs</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>When a directive tag is closed implicitly AND there is no other
text on the line, the ENTIRE line is gobbled up including any
preceeding whitespace:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo</span>
<span class="sd">   #set $x = 2</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">outputs</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="k">while</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo</span>
<span class="sd"> - #set $x = 2</span>
<span class="sd">bar</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">outputs</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">foo</span>
<span class="sd"> - bar</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>The {#slurp} directive (section output.slurp) also gobbles up
whitespace.</p>
<p>Spaces outside directives are output { exactly} as written. In the
black sheep example, there’s a space before “black” and another
before “sheep”. So although it’s legal to put multiple directives
on one line, it can be hard to read.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>#if $a# #echo $a + 1# #end if
      - There&#39;s a space between each directive,
        or two extra spaces total.
#if $a##echo $a + 1##end if
      - No spaces, but you have to look closely
        to verify none of the ``##&#39;&#39; are comment markers.
#if $a##echo $a + 1##end if     ### A comment.
      - In ``###&#39;&#39;, the first ``#&#39;&#39; ends the directive,
        the other two begin the comment.  (This also shows
    how you can add extra whitespace in the directive
    tag without affecting the output.)
#if $a##echo $a + 1##end if     # ## A comment.
      - More readable, but now there&#39;s a space before the
        comment.
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="comments.html" title="Comments"
             >next</a> |</li>
        <li class="right" >
          <a href="gettingStarted.html" title="Getting Started"
             >previous</a> |</li>
        <li class="nav-item nav-item-0"><a href="../index.html">Cheetah3 - The Python-Powered Template Engine</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="index.html" >Cheetah User’s Guide</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2017, Oleg Broytman; 2009-2012, R. Tyler Croy; 2001-2008, The Cheetah Development Team..
      Last updated on Mar 03, 2018.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.5.
    </div>
  </body>
</html>