Mercurial > genshi > mirror
annotate doc/xml-templates.txt @ 427:55c574767df2 trunk
More API documentation.
author | cmlenz |
---|---|
date | Thu, 22 Mar 2007 15:05:29 +0000 |
parents | ee17693d2976 |
children | 691dd56c0dd0 |
rev | line source |
---|---|
226 | 1 .. -*- mode: rst; encoding: utf-8 -*- |
2 | |
3 ============================ | |
230 | 4 Genshi XML Template Language |
226 | 5 ============================ |
6 | |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
7 Genshi provides a XML-based template language that is heavily inspired by Kid_, |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
8 which in turn was inspired by a number of existing template languages, namely |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
9 XSLT_, TAL_, and PHP_. |
226 | 10 |
11 .. _kid: http://kid-templating.org/ | |
12 .. _python: http://www.python.org/ | |
13 .. _xslt: http://www.w3.org/TR/xslt | |
14 .. _tal: http://www.zope.org/Wikis/DevSite/Projects/ZPT/TAL | |
15 .. _php: http://www.php.net/ | |
16 | |
17 This document describes the template language and will be most useful as | |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
18 reference to those developing Genshi XML templates. Templates are XML files of |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
19 some kind (such as XHTML) that include processing directives_ (elements or |
226 | 20 attributes identified by a separate namespace) that affect how the template is |
21 rendered, and template expressions_ that are dynamically substituted by | |
22 variable data. | |
23 | |
24 | |
25 .. contents:: Contents | |
26 :depth: 3 | |
27 .. sectnum:: | |
28 | |
29 ---------- | |
30 Python API | |
31 ---------- | |
32 | |
230 | 33 The Python code required for templating with Genshi is generally based on the |
226 | 34 following pattern: |
35 | |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
36 * Attain a ``MarkupTemplate`` object from a string or file object containing |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
37 the template XML source. This can either be done directly, or through a |
226 | 38 ``TemplateLoader`` instance. |
39 * Call the ``generate()`` method of the template, passing any data that should | |
40 be made available to the template as keyword arguments. | |
41 * Serialize the resulting stream using its ``render()`` method. | |
42 | |
43 For example:: | |
44 | |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
45 from genshi.template import MarkupTemplate |
226 | 46 |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
47 tmpl = MarkupTemplate('<h1>$title</h1>') |
226 | 48 stream = tmpl.generate(title='Hello, world!') |
49 print stream.render('xhtml') | |
50 | |
51 That code would produce the following output:: | |
52 | |
53 <h1>Hello, world!</h1> | |
54 | |
55 However, if you want includes_ to work, you should attain the template instance | |
56 through a ``TemplateLoader``, and load the template from a file:: | |
57 | |
230 | 58 from genshi.template import TemplateLoader |
226 | 59 |
60 loader = TemplateLoader([templates_dir]) | |
61 tmpl = loader.load('test.html') | |
62 stream = tmpl.generate(title='Hello, world!') | |
63 print stream.render('xhtml') | |
64 | |
65 | |
66 .. _`expressions`: | |
67 | |
68 -------------------- | |
69 Template Expressions | |
70 -------------------- | |
71 | |
72 Python_ expressions can be used in text and attribute values. An expression is | |
73 substituted with the result of its evaluation against the template data. | |
74 Expressions need to prefixed with a dollar sign (``$``) and usually enclosed in | |
75 curly braces (``{…}``). | |
76 | |
394 | 77 If the expression starts with a letter and contains only letters, digits, dots, |
78 and underscores, the curly braces may be omitted. In all other cases, the | |
79 braces are required so that the template processor knows where the expression | |
80 ends:: | |
226 | 81 |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
82 >>> from genshi.template import MarkupTemplate |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
83 >>> tmpl = MarkupTemplate('<em>${items[0].capitalize()} item</em>') |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
84 >>> print tmpl.generate(items=['first', 'second']) |
226 | 85 <em>First item</em> |
86 | |
87 Expressions support the full power of Python. In addition, it is possible to | |
88 access items in a dictionary using “dotted notation” (i.e. as if they were | |
89 attributes), and vice-versa (i.e. access attributes as if they were items in a | |
90 dictionary):: | |
91 | |
241
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
92 >>> from genshi.template import MarkupTemplate |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
93 >>> tmpl = MarkupTemplate('<em>${dict.foo}</em>') |
4d81439bc097
* Added basic documentation for the text-based template language.
cmlenz
parents:
237
diff
changeset
|
94 >>> print tmpl.generate(dict={'foo': 'bar'}) |
226 | 95 <em>bar</em> |
96 | |
244 | 97 Another difference is that you can access variables that are not defined, and |
98 won't get a ``NameError`` exception:: | |
99 | |
100 >>> from genshi.template import TextTemplate | |
101 >>> tmpl = TextTemplate('${doh}') | |
102 >>> print tmpl.generate() | |
103 <BLANKLINE> | |
104 | |
105 You **will** however get a ``NameError`` if you try to call an undefined | |
106 variable, or do anything else with it, such as accessing its attributes. If you | |
107 need to know whether a variable is defined, you can check its type against the | |
354 | 108 ``Undefined`` class, for example in a `py:if`_ directive:: |
244 | 109 |
110 >>> from genshi.template import TextTemplate | |
111 >>> tmpl = TextTemplate('${type(doh) is Undefined}') | |
112 >>> print tmpl.generate() | |
113 True | |
114 | |
226 | 115 |
116 .. _`directives`: | |
117 | |
118 ------------------- | |
119 Template Directives | |
120 ------------------- | |
121 | |
122 Directives are elements and/or attributes in the template that are identified | |
230 | 123 by the namespace ``http://genshi.edgewall.org/``. They can affect how the |
124 template is rendered in a number of ways: Genshi provides directives for | |
226 | 125 conditionals and looping, among others. |
126 | |
394 | 127 To use directives in a template, the namespace must be declared, which is |
226 | 128 usually done on the root element:: |
129 | |
130 <html xmlns="http://www.w3.org/1999/xhtml" | |
230 | 131 xmlns:py="http://genshi.edgewall.org/" |
226 | 132 lang="en"> |
133 ... | |
134 </html> | |
135 | |
136 In this example, the default namespace is set to the XHTML namespace, and the | |
230 | 137 namespace for Genshi directives is bound to the prefix “py”. |
226 | 138 |
139 All directives can be applied as attributes, and some can also be used as | |
140 elements. The ``if`` directives for conditionals, for example, can be used in | |
141 both ways:: | |
142 | |
143 <html xmlns="http://www.w3.org/1999/xhtml" | |
230 | 144 xmlns:py="http://genshi.edgewall.org/" |
226 | 145 lang="en"> |
146 ... | |
147 <div py:if="foo"> | |
148 <p>Bar</p> | |
149 </div> | |
150 ... | |
151 </html> | |
152 | |
153 This is basically equivalent to the following:: | |
154 | |
155 <html xmlns="http://www.w3.org/1999/xhtml" | |
230 | 156 xmlns:py="http://genshi.edgewall.org/" |
226 | 157 lang="en"> |
158 ... | |
159 <py:if test="foo"> | |
160 <div> | |
161 <p>Bar</p> | |
162 </div> | |
163 </py:if> | |
164 ... | |
165 </html> | |
166 | |
167 The rationale behind the second form is that directives do not always map | |
168 naturally to elements in the template. In such cases, the ``py:strip`` | |
169 directive can be used to strip off the unwanted element, or the directive can | |
170 simply be used as an element. | |
171 | |
172 | |
237 | 173 Conditional Sections |
226 | 174 ==================== |
175 | |
235 | 176 .. _`py:if`: |
226 | 177 |
235 | 178 ``py:if`` |
237 | 179 --------- |
226 | 180 |
235 | 181 The element is only rendered if the expression evaluates to a truth value:: |
226 | 182 |
235 | 183 <div> |
184 <b py:if="foo">${bar}</b> | |
185 </div> | |
226 | 186 |
235 | 187 Given the data ``foo=True`` and ``bar='Hello'`` in the template context, this |
188 would produce:: | |
189 | |
190 <div> | |
191 <b>Hello</b> | |
192 </div> | |
193 | |
194 This directive can also be used as an element:: | |
195 | |
196 <div> | |
197 <py:if test="foo"> | |
198 <b>${bar}</b> | |
199 </py:if> | |
200 </div> | |
226 | 201 |
202 .. _`py:choose`: | |
203 .. _`py:when`: | |
204 .. _`py:otherwise`: | |
205 | |
237 | 206 ``py:choose`` |
207 ------------- | |
226 | 208 |
237 | 209 The ``py:choose`` directive, in combination with the directives ``py:when`` |
404 | 210 and ``py:otherwise`` provides advanced conditional processing for rendering one |
226 | 211 of several alternatives. The first matching ``py:when`` branch is rendered, or, |
404 | 212 if no ``py:when`` branch matches, the ``py:otherwise`` branch is rendered. |
226 | 213 |
214 If the ``py:choose`` directive is empty the nested ``py:when`` directives will | |
215 be tested for truth:: | |
216 | |
217 <div py:choose=""> | |
218 <span py:when="0 == 1">0</span> | |
219 <span py:when="1 == 1">1</span> | |
220 <span py:otherwise="">2</span> | |
221 </div> | |
222 | |
223 This would produce the following output:: | |
224 | |
225 <div> | |
226 <span>1</span> | |
227 </div> | |
228 | |
229 If the ``py:choose`` directive contains an expression the nested ``py:when`` | |
230 directives will be tested for equality to the parent ``py:choose`` value:: | |
231 | |
232 <div py:choose="1"> | |
233 <span py:when="0">0</span> | |
234 <span py:when="1">1</span> | |
235 <span py:otherwise="">2</span> | |
236 </div> | |
237 | |
238 This would produce the following output:: | |
239 | |
240 <div> | |
241 <span>1</span> | |
242 </div> | |
243 | |
244 | |
235 | 245 Looping |
237 | 246 ======= |
226 | 247 |
235 | 248 .. _`py:for`: |
226 | 249 |
235 | 250 ``py:for`` |
237 | 251 ---------- |
235 | 252 |
253 The element is repeated for every item in an iterable:: | |
226 | 254 |
255 <ul> | |
235 | 256 <li py:for="item in items">${item}</li> |
226 | 257 </ul> |
258 | |
235 | 259 Given ``items=[1, 2, 3]`` in the context data, this would produce:: |
226 | 260 |
261 <ul> | |
235 | 262 <li>1</li><li>2</li><li>3</li> |
226 | 263 </ul> |
264 | |
235 | 265 This directive can also be used as an element:: |
226 | 266 |
235 | 267 <ul> |
268 <py:for each="item in items"> | |
269 <li>${item}</li> | |
270 </py:for> | |
271 </ul> | |
272 | |
273 | |
274 Snippet Reuse | |
237 | 275 ============= |
226 | 276 |
277 .. _`py:def`: | |
278 .. _`macros`: | |
279 | |
280 ``py:def`` | |
237 | 281 ---------- |
226 | 282 |
283 The ``py:def`` directive can be used to create macros, i.e. snippets of | |
284 template code that have a name and optionally some parameters, and that can be | |
285 inserted in other places:: | |
286 | |
287 <div> | |
288 <p py:def="greeting(name)" class="greeting"> | |
289 Hello, ${name}! | |
290 </p> | |
291 ${greeting('world')} | |
292 ${greeting('everyone else')} | |
293 </div> | |
294 | |
295 The above would be rendered to:: | |
296 | |
297 <div> | |
298 <p class="greeting"> | |
299 Hello, world! | |
300 </p> | |
301 <p class="greeting"> | |
302 Hello, everyone else! | |
303 </p> | |
304 </div> | |
305 | |
394 | 306 If a macro doesn't require parameters, it can be defined without the |
307 parenthesis. For example:: | |
226 | 308 |
309 <div> | |
310 <p py:def="greeting" class="greeting"> | |
311 Hello, world! | |
312 </p> | |
394 | 313 ${greeting()} |
226 | 314 </div> |
315 | |
316 The above would be rendered to:: | |
317 | |
318 <div> | |
319 <p class="greeting"> | |
320 Hello, world! | |
321 </p> | |
322 </div> | |
323 | |
324 This directive can also be used as an element:: | |
325 | |
326 <div> | |
327 <py:def function="greeting(name)"> | |
328 <p class="greeting">Hello, ${name}!</p> | |
329 </py:def> | |
330 </div> | |
331 | |
332 | |
235 | 333 .. _Match Templates: |
226 | 334 .. _`py:match`: |
335 | |
336 ``py:match`` | |
237 | 337 ------------ |
226 | 338 |
339 This directive defines a *match template*: given an XPath expression, it | |
340 replaces any element in the template that matches the expression with its own | |
341 content. | |
342 | |
343 For example, the match template defined in the following template matches any | |
344 element with the tag name “greeting”:: | |
345 | |
346 <div> | |
347 <span py:match="greeting"> | |
348 Hello ${select('@name')} | |
349 </span> | |
350 <greeting name="Dude" /> | |
351 </div> | |
352 | |
353 This would result in the following output:: | |
354 | |
355 <div> | |
356 <span> | |
357 Hello Dude | |
358 </span> | |
359 </div> | |
360 | |
361 Inside the body of a ``py:match`` directive, the ``select(path)`` function is | |
362 made available so that parts or all of the original element can be incorporated | |
230 | 363 in the output of the match template. See [wiki:GenshiStream#UsingXPath] for |
226 | 364 more information about this function. |
365 | |
366 This directive can also be used as an element:: | |
367 | |
368 <div> | |
369 <py:match path="greeting"> | |
370 <span>Hello ${select('@name')}</span> | |
371 </py:match> | |
372 <greeting name="Dude" /> | |
373 </div> | |
374 | |
375 | |
235 | 376 Variable Binding |
237 | 377 ================ |
226 | 378 |
379 .. _`with`: | |
380 | |
381 ``py:with`` | |
237 | 382 ----------- |
226 | 383 |
384 The ``py:with`` directive lets you assign expressions to variables, which can | |
385 be used to make expressions inside the directive less verbose and more | |
386 efficient. For example, if you need use the expression ``author.posts`` more | |
387 than once, and that actually results in a database query, assigning the results | |
388 to a variable using this directive would probably help. | |
389 | |
390 For example:: | |
391 | |
392 <div> | |
393 <span py:with="y=7; z=x+10">$x $y $z</span> | |
394 </div> | |
395 | |
396 Given ``x=42`` in the context data, this would produce:: | |
397 | |
398 <div> | |
399 <span>42 7 52</span> | |
400 </div> | |
401 | |
402 This directive can also be used as an element:: | |
403 | |
404 <div> | |
405 <py:with vars="y=7; z=x+10">$x $y $z</py:with> | |
406 </div> | |
407 | |
408 Note that if a variable of the same name already existed outside of the scope | |
409 of the ``py:with`` directive, it will **not** be overwritten. Instead, it | |
410 will have the same value it had prior to the ``py:with`` assignment. | |
230 | 411 Effectively, this means that variables are immutable in Genshi. |
226 | 412 |
413 | |
235 | 414 Structure Manipulation |
237 | 415 ====================== |
235 | 416 |
417 .. _`py:attrs`: | |
418 | |
419 ``py:attrs`` | |
237 | 420 ------------ |
235 | 421 |
422 This directive adds, modifies or removes attributes from the element:: | |
423 | |
424 <ul> | |
425 <li py:attrs="foo">Bar</li> | |
426 </ul> | |
427 | |
428 Given ``foo={'class': 'collapse'}`` in the template context, this would | |
429 produce:: | |
430 | |
431 <ul> | |
432 <li class="collapse">Bar</li> | |
433 </ul> | |
434 | |
435 Attributes with the value ``None`` are omitted, so given ``foo={'class': None}`` | |
436 in the context for the same template this would produce:: | |
437 | |
438 <ul> | |
439 <li>Bar</li> | |
440 </ul> | |
441 | |
442 This directive can only be used as an attribute. | |
443 | |
444 | |
445 .. _`py:content`: | |
446 | |
447 ``py:content`` | |
237 | 448 -------------- |
235 | 449 |
450 This directive replaces any nested content with the result of evaluating the | |
451 expression:: | |
452 | |
453 <ul> | |
454 <li py:content="bar">Hello</li> | |
455 </ul> | |
456 | |
457 Given ``bar='Bye'`` in the context data, this would produce:: | |
458 | |
459 <ul> | |
460 <li>Bye</li> | |
461 </ul> | |
462 | |
463 This directive can only be used as an attribute. | |
464 | |
465 | |
466 .. _`py:replace`: | |
467 | |
468 ``py:replace`` | |
237 | 469 -------------- |
235 | 470 |
471 This directive replaces the element itself with the result of evaluating the | |
472 expression:: | |
473 | |
474 <div> | |
475 <span py:replace="bar">Hello</span> | |
476 </div> | |
477 | |
478 Given ``bar='Bye'`` in the context data, this would produce:: | |
479 | |
480 <div> | |
481 Bye | |
482 </div> | |
483 | |
484 This directive can only be used as an attribute. | |
485 | |
486 | |
487 .. _`py:strip`: | |
488 | |
489 ``py:strip`` | |
237 | 490 ------------ |
235 | 491 |
492 This directive conditionally strips the top-level element from the output. When | |
493 the value of the ``py:strip`` attribute evaluates to ``True``, the element is | |
494 stripped from the output:: | |
495 | |
496 <div> | |
497 <div py:strip="True"><b>foo</b></div> | |
498 </div> | |
499 | |
500 This would be rendered as:: | |
501 | |
502 <div> | |
503 <b>foo</b> | |
504 </div> | |
505 | |
506 As a shorthand, if the value of the ``py:strip`` attribute is empty, that has | |
507 the same effect as using a truth value (i.e. the element is stripped). | |
508 | |
509 | |
226 | 510 .. _order: |
511 | |
512 Processing Order | |
513 ================ | |
514 | |
515 It is possible to attach multiple directives to a single element, although not | |
516 all combinations make sense. When multiple directives are encountered, they are | |
517 processed in the following order: | |
518 | |
519 #. `py:def`_ | |
520 #. `py:match`_ | |
521 #. `py:when`_ | |
522 #. `py:otherwise`_ | |
523 #. `py:for`_ | |
524 #. `py:if`_ | |
525 #. `py:choose`_ | |
526 #. `py:with`_ | |
527 #. `py:replace`_ | |
528 #. `py:content`_ | |
529 #. `py:attrs`_ | |
530 #. `py:strip`_ | |
531 | |
532 | |
533 .. _includes: | |
534 | |
535 -------- | |
536 Includes | |
537 -------- | |
538 | |
539 To reuse common snippets of template code, you can include other files using | |
540 XInclude_. | |
541 | |
542 .. _xinclude: http://www.w3.org/TR/xinclude/ | |
543 | |
544 For this, you need to declare the XInclude namespace (commonly bound to the | |
545 prefix “xi”) and use the ``<xi:include>`` element where you want the external | |
546 file to be pulled in:: | |
547 | |
548 <html xmlns="http://www.w3.org/1999/xhtml" | |
230 | 549 xmlns:py="http://genshi.edgewall.org/" |
226 | 550 xmlns:xi="http://www.w3.org/2001/XInclude"> |
551 <xi:include href="base.html" /> | |
552 ... | |
553 </html> | |
554 | |
555 Include paths are relative to the filename of the template currently being | |
556 processed. So if the example above was in the file "``myapp/index.html``" | |
557 (relative to the template search path), the XInclude processor would look for | |
558 the included file at "``myapp/base.html``". You can also use Unix-style | |
559 relative paths, for example "``../base.html``" to look in the parent directory. | |
560 | |
561 Any content included this way is inserted into the generated output instead of | |
562 the ``<xi:include>`` element. The included template sees the same context data. | |
563 `Match templates`_ and `macros`_ in the included template are also available to | |
564 the including template after the point it was included. | |
565 | |
566 By default, an error will be raised if an included file is not found. If that's | |
567 not what you want, you can specify fallback content that should be used if the | |
568 include fails. For example, to to make the include above fail silently, you'd | |
273 | 569 write:: |
226 | 570 |
571 <xi:include href="base.html"><xi:fallback /></xi:include> | |
572 | |
273 | 573 See the `XInclude specification`_ for more about fallback content. Note though |
574 that Genshi currently only supports a small subset of XInclude. | |
575 | |
576 .. _`xinclude specification`: http://www.w3.org/TR/xinclude/ | |
226 | 577 |
230 | 578 Incudes in Genshi are fully dynamic: Just like normal attributes, the `href` |
226 | 579 attribute accepts expressions_, and directives_ can be used on the |
580 ``<xi:include />`` element just as on any other element, meaning you can do | |
581 things like conditional includes:: | |
582 | |
583 <xi:include href="${name}.html" py:if="not in_popup" | |
584 py:for="name in ('foo', 'bar', 'baz')" /> | |
585 | |
586 | |
587 .. _comments: | |
588 | |
589 -------- | |
590 Comments | |
591 -------- | |
592 | |
593 Normal XML/HTML comment syntax can be used in templates:: | |
594 | |
595 <!-- this is a comment --> | |
596 | |
597 However, such comments get passed through the processing pipeline and are by | |
598 default included in the final output. If that's not desired, prefix the comment | |
599 text with an exclamation mark:: | |
600 | |
601 <!-- !this is a comment too, but one that will be stripped from the output --> | |
602 | |
603 Note that it does not matter whether there's whitespace before or after the | |
604 exclamation mark, so the above could also be written as follows:: | |
605 | |
606 <!--! this is a comment too, but one that will be stripped from the output --> |