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