root/livinglogic.python.xist/docs/UL4.rst @ 5322:23a99cbbf7f8

Revision 5322:23a99cbbf7f8, 32.4 KB (checked in by Walter Doerwald <walter@…>, 7 years ago)

Rename <?exe?> back to <?code?>.

Line 
1:mod:`ll.ul4c` provides templating for XML/HTML as well as any other text-based
2format. A template defines placeholders for data output and basic logic (like
3loops and conditional blocks), that define how the final rendered output will
4look.
5
6:mod:`ll.ul4c` compiles a template to an internal format, which makes it
7possible to implement renderers for these templates in multiple programming
8languages.
9
10Apart from this Python implementaion there are implementations for Java_ (both a
11compiler and renderer), Javascript_ (renderer only) and PHP_ (renderer only).
12
13.. _Java: http://hg.livinglogic.de/LivingLogic.Java.ul4/
14.. _Javascript: http://hg.livinglogic.de/LivingLogic.Javascript.ul4/
15.. _PHP: http://hg.livinglogic.de/LivingLogic.PHP.ul4/
16
17
18Embedding
19=========
20
21In the template source any text surrounded by ``<?`` and ``?>`` is a "template
22tag". The first word inside the tag is the tag type. It defines what the tag
23does. For example ``<?print foo?>`` is a print tag (it prints the value of the
24variable ``foo``). A complete example template looks like this::
25
26    <?if data?>
27    <ul>
28    <?for item in data?>
29    <li><?print xmlescape(item)?></li>
30    <?end for?>
31    </ul>
32    <?end if?>
33
34(For text formats where the delimiters ``<?`` and ``?>`` collide with elements
35that are used often or where using these delimiters is inconvenient it's
36possible to specify a different delimiter pair when compiling the template.)
37
38A complete Python program that compiles a template and renders it might look
39like this::
40
41    from ll import ul4c
42
43    code = '''
44        <?if data?>
45            <ul>
46                <?for item in data?>
47                    <li><?print item?></li>
48                <?end for?>
49            </ul>
50        <?end if?>
51    '''
52
53    template = ul4c.Template(code)
54
55    print(template.renders(data=["Python", "Java", "Javascript", "PHP"]))
56
57The variables that should be available to the template code can be passed to the
58method :meth:`Template.renders` as keyword arguments. :meth:`renders` returns
59the final rendered output as a string. Alternatively the method :meth:`render`
60can be used, which is a generator and returns the output piecewise.
61
62
63Supported data types
64====================
65
66The following object types can be passed as variables to be used by the template
67code:
68
69*   strings
70*   integers
71*   floats
72*   date objects
73*   color objects
74*   The "null" value (``None``)
75*   boolean values (``True`` and ``False``)
76*   the ``Undefined`` variable
77*   lists
78*   dictionaries
79*   UL4 templates
80
81This is similar to what JSON_ supports (except for date objects, color objects,
82UL4 templates).
83
84    .. _JSON: http://www.json.org/
85
86Note that depending on the implementation language of the renderer additional
87types might be supported, e.g. a Python renderer will probably support tuples
88and lists and anything supporting :meth:`__getitem__` (or :meth:`__iter__` when
89the list is used in a loop) for lists, Java might support anything implementing
90the ``List`` interface (or the ``Collection`` interface if the list is used in a
91loop).
92
93Objects of these types can either be passed to the template in the call to the
94render function, or the template can create objects of thoses types itself. The
95syntax for creating such a constant is very similar to Python's syntax.
96
97
98The "null" constant
99-------------------
100
101The "null" constant can be referred to via ``None``.
102
103
104Boolean constants
105-----------------
106
107The boolean constants can be referred to via ``True`` and ``False``.
108
109
110Integer constants
111-----------------
112
113Integer constants can be written in decimal, hexadecimal, octal and binary:
114``42``, ``0x2a``, ``0o52`` and ``0b101010`` all refer to the integer value 42.
115
116
117Float constants
118---------------
119
120Float constants must contain a decimal point or an exponential specifier,
121e.g. ``42.``, ``4e23``.
122
123
124String constants
125----------------
126
127Strings are delimited with single or double quotes and support all escape
128sequences that Python supports (except ``\N{}``). Strings constants are always
129unicode objects, so ``\uXXXX`` escaping is possible. Examples:
130
131* ``"abc"`` and ``'abc'``;
132
133*   ``"'"`` and ``'\''`` are single quotes;
134
135*   ``'"'`` and ``"\""`` are double quotes;
136
137*   ``"\n"`` is a line feed and ``"\t"`` is a tab;
138
139*   ``"\x61"`` and ``"\u0061"`` are lowercase "a"s;
140
141
142Date constants
143--------------
144
145Date objects have a date and time including microseconds. Date constants can be
146created like this:
147
148*   ``@(2008-12-24)``
149
150*   ``@(2008-12-24T12:34)``
151
152*   ``@(2008-12-24T12:34:56)``
153
154*   ``@(2008-12-24T12:34:56.987654)``
155
156
157Color constants
158---------------
159
160Color values are 8 bit red, green, blue and alpha values. Color constants can
161be created like this:
162
163*   ``#fff``
164
165*   ``#fff8``
166
167*   ``#0063a8``
168
169*   ``#0063a880``
170
171The variants with 3 or 6 hex digits will create a color object with an alpha
172value of 255.
173
174
175Lists
176-----
177
178Lists can be created like this:
179
180*   ``[]``
181
182*   ``[1, 2, 3]``
183
184*   ``[None, 42, "foo", [False, True]]``
185
186It is also possible to create a list with a list comprehension::
187
188    ["(" + c.upper() + ")" for c in "hurz" if c < "u"]
189
190This will create the list::
191
192    ["(H)", "(R)"]
193
194The ``if`` condition is optional, i.e.::
195
196    ["(" + c.upper() + ")" for c in "hurz"]
197
198will create the list::
199
200    ["(H)", "(U)", "(R)", "(Z)"]
201
202
203Dictionaries
204------------
205
206Dictionaries can be created like this:
207
208*   ``{}``
209
210*   ``{1: 2, 3: 4}``
211
212*   ``{"foo": 17, "bar": 23}``
213
214Also Python ``**`` syntax for passing keyword arguments is supported for
215creating dictionaries::
216
217    {"foo": 17, "bar": 23, **{1: 2, 3: 4}}
218
219With this it's possible to copy the content of one dictionary into another new
220one. Keys are set from left to right, so later values overwrite former ones, so
221``{1: 2, 1: 3}[1]`` and ``{1: 2, **{1: 3}}[1]`` will both return ``3`` not ``2``.
222
223It is also possible to create a dictionary with a dictionary comprehension::
224
225    { c.upper() : "(" + c + ")" for c in "hurz" if c < "u"}
226
227This will create the dictionary::
228
229    { "H": "(h)", "R": "(r)"}
230
231The ``if`` condition is optional, i.e.::
232
233    { c.upper() : "(" + c + ")" for c in "hurz"}
234
235will create the dictionary::
236
237    { "H": "(h)", "R": "(r)", "U": "(u)", "Z": "(z)"}
238
239
240The ``Undefined`` object
241------------------------
242
243The object ``Undefined`` will be returned when a non-existant variable, a
244non-existant dictionary entry or an index that is out of range for a list/string
245is accessed.
246
247
248Template code
249=============
250
251The template code tries to mimic Python syntax as far as possible, but is
252limited to what is required for templates and does not allow executing arbitrary
253Python statements. In some spots it also borrows Javascript semantics.
254
255:mod:`ll.ul4c` supports the following tag types:
256
257
258``print``
259---------
260
261The ``print`` tag outputs the value of a variable or any other expression. If
262the expression doesn't evaluate to a string it will be converted to a string
263first. The format of the string depends on the renderer, but should follow
264Python's ``str()`` output as much as possible (except that for ``None`` no
265output may be produced)::
266
267    <h1><?print person.lastname?>, <?print person.firstname?></h1>
268
269
270``printx``
271----------
272
273The ``printx`` tag outputs the value of a variable or any other expression and
274escapes the characters ``<``, ``>``, ``&``, ``'`` and ``"`` with the appropriate
275character or entity references for XML or HTML output.
276
277
278``for``
279-------
280
281The ``for`` tag can be used to loop over the items in a list, the characters in
282a string or the keys in a dictionary. The end of the loop body must be marked
283with an ``<?end for?>`` tag::
284
285    <ul>
286    <?for person in data.persons?>
287    <li><?print person.lastname?>, <?person.firstname?></li>
288    <?end for?>
289    </ul>
290
291In ``for`` loops variable unpacking is supported, so you can do the following::
292
293    <?for (key, value) in dict.items()?>
294
295if ``dict`` is a dictionary.
296
297This unpacking can be arbitrarily nested, i.e. the following is possible too::
298
299    <?for (i, (key, value)) in enumerate(dict.items())?>
300
301
302``break``
303---------
304
305The ``break`` tag can be used to break out of the innermost running loop.
306
307
308``continue``
309------------
310
311The ``continue`` tag can be used to skip the rest of the loop body of the
312innermost running loop.
313
314
315``if``
316------
317
318The ``if`` tag can be used to output a part of the template only when a
319condition is true. The end of the ``if`` block must be marked with an
320``<?end if?>`` tag. The truth value of an object is mostly the same as in Python:
321
322*   ``None`` is false.
323*   The integer ``0`` and the float value ``0.0`` are false.
324*   Empty strings, lists and dictionaries are false.
325*   ``timedelta`` and ``monthdelta`` objects for an empty timespan (i.e.
326    ``timedelta(0, 0, 0)`` and ``monthdelta(0)``) are false.
327*   ``False`` is false.
328*   ``Undefined`` is false.
329*   Anything else is true.
330
331For example we can output the person list only if there are any persons::
332
333    <?if persons?>
334    <ul>
335    <?for person in persons?>
336    <li><?print person.lastname?>, <?person.firstname?></li>
337    <?end for?>
338    </ul>
339    <?end if?>
340
341``elif`` and ``else`` are supported too::
342
343    <?if persons?>
344    <ul>
345    <?for person in persons?>
346    <li><?print person.lastname?>, <?person.firstname?></li>
347    <?end for?>
348    </ul>
349    <?else?>
350    <p>No persons found!</p>
351    <?end if?>
352
353or::
354
355    <?if len(persons)==0?>
356    No persons found!
357    <?elif len(persons)==1?>
358    One person found!
359    <?else?>
360    <?print len(persons)?> persons found!
361    <?end if?>
362
363
364``code``
365--------
366
367The ``code`` tag can contain statements that define or modify variables or
368expressions which will be evaluated for their side effects. Apart from the
369assigment operator ``=``, the following augmented assignment operators are
370supported:
371
372*   ``+=`` (adds a value to the variable)
373*   ``-=`` (subtracts a value from the variable)
374*   ``*=`` (multiplies the variable by a value)
375*   ``/=`` (divides the variable by a value)
376*   ``//=`` (divides the variable by a value, rounding down to the next
377    smallest integer)
378*   ``&=`` (Does a modulo operation and replaces the variable value with the
379    result)
380
381For example the following template will output ``40``::
382
383    <?code x = 17?>
384    <?code x += 23?>
385    <?print x?>
386
387
388``def``
389-------
390
391The ```def`` tag defined a new template as a variable. Usage looks like this::
392
393    <?def quote?>"<?print text?>"<?end def?>
394
395This defines a local variable ``quote`` that is a template object. This template
396can be called like any other template, that has been passed to the outermost
397template::
398
399    <?code quote.render(text="foo")?>
400
401(Here an ``<?code?>`` tag is used. The expression in the ``<?code?>`` tag is
402evaluated for the side effect of generating output)
403
404
405``note``
406--------
407
408A ``note`` tag is a comment, i.e. the content of the tag will be completely ignored.
409
410
411Nested scopes
412-------------
413
414UL4 templates support lexical scopes. This means that a template that is defined
415(via ``<?template?>``) inside another template has access to the local variables
416of the outer template. The inner template sees that state of the variables at
417the point in time when the ``<?template?>`` tag was executed. The following
418example will output ``1``::
419
420    <?code i = 1?>
421    <?template x?>
422        <?print i?>
423    <?end template?>
424    <?code i = 2?>
425    <?render x.render()?>
426
427
428Expressions
429-----------
430
431:mod:`ll.ul4c` supports many of the operators supported by Python. Getitem style
432element access is available, i.e. in the expression ``a[b]`` the following type
433combinations are supported:
434
435*   string, integer: Returns the ``b``\th character from the string ``a``.
436    Note that negative ``b`` values are supported and are relative to the end,
437    so ``a[-1]`` is the last character.
438
439*   list, integer: Returns the ``b``\th list entry of the list ``a``. Negative
440    ``b`` values are supported too.
441
442*   dict, string: Return the value from the dictionary ``a`` corresponding to
443    the key ``b``. Note that some implementations might support keys other
444    than strings too. (The Python and Java renderer do for example.)
445
446If the specified key doesn't exist or the index is out of range for the string
447or list, the special object ``Undefined`` is returned.
448
449Slices are also supported (for list and string objects). As in Python one or
450both of the indexes may be missing to start at the first or end after the last
451character/item. Negative indexes are relative to the end. Indexes that are out
452of bounds are simply clipped:
453
454*   ``<?print "Hello, World!"[7:-1]?>`` prints ``World``.
455
456*   ``<?print "Hello, World!"[:-8]?>`` prints ``Hello``.
457
458The following binary operators are supported: ``+``, ``-``, ``*``, ``/`` (true
459division), ``//`` (truncating division) and ``&`` (modulo).
460
461The usual boolean operators ``not``, ``and`` and ``or`` are supported. ``and``
462and ``or`` work like in Python, i.e. they short-circuit, i.e. if they result is
463clear from the first operand the seconds won't be evaluated, Furthermore they
464always return one of the operands). For example, the following code will output
465the ``data.title`` object if it's true, else ``data.id`` will be output::
466
467    <?print xmlescape(data.title or data.id)?>
468
469The comparison operators ``==``, ``!=``, ``<``, ``<=``, ``>`` and ``>=`` are
470supported.
471
472Containment test via the ``in`` operator can be done, in the expression
473``a in b`` the following type combinations are supported:
474
475*   string, string: Checks whether ``a`` is a substring of ``b``.
476*   any object, list: Checks whether the object ``a`` is in the list ``b``
477    (comparison is done by value not by identity)
478*   string, dict: Checks whether the key ``a`` is in the dictionary ``b``.
479    (Note that some implementations might support keys other than strings too.
480    E.g. Python and Java do, Javascript doesn't.)
481
482The inverted containment test (via ``not in``) is available too.
483
484Attribute access in the template code maps to dictionary style getitem access
485in the data object::
486
487    from ll import ul4c
488    tmpl = ul4c.Template("<?print data.foo?>")
489    print(tmpl.renders(data=dict(foo="bar")))
490
491However getitem style access in the template is still possible::
492
493    from ll import ul4c
494    tmpl = ul4c.Template("<?print data['foo']?>")
495    print(tmpl.renders(data=dict(foo="bar")))
496
497UL4 also supports generator expressions::
498
499    <?print ", ".join("(" + c + ")" for c in "gurk")?>
500
501will output::
502
503    (g), (u), (r), (k)
504
505Outside of function/method arguments brackets are required around generator
506expressions::
507
508    <?code ge = ("(" + c + ")" for c in "gurk")?>
509    <?print ", ".join(ge)?>
510
511
512Functions
513---------
514
515:mod:`ll.ul4c` supports a number of functions.
516
517
518``now``
519"""""""
520
521``now()`` returns the current date and time as a date object.
522
523
524``utcnow``
525""""""""""
526
527``utcnow()`` returns the current date and time as a date object in UTC.
528
529
530``date``
531""""""""
532
533``date()`` creates a date object from the parameter passed in. ``date()``
534supports from three parameters (year, month, day) upto seven parameters
535(year, month, day, hour, minute, second, microsecond).
536
537
538``timedelta``
539"""""""""""""
540
541``timedelta`` returns an object that represents a timespan. ``timedelta``
542allows from zero to three arguments specifying the numbers of days, seconds and
543microseconds. Passing negative values or values that are out of bounds (e.g.
54424*60*60+1 seconds) is allowed. Arguments default to 0, i.e. ``timedelta()``
545returns the timespan for "0 days, 0 seconds, 0 microseconds". In a boolean
546context this object is treated as false (i.e. ``bool(timedelta()))`` returns
547``False``). The following arithmetic operations are supported::
548
549*   ``date`` + ``timedelta``
550*   ``date`` - ``timedelta``
551*   ``timedelta`` + ``timedelta``
552*   ``timedelta`` - ``timedelta``
553*   ``number`` * ``timedelta``
554*   ``timedelta`` * ``number``
555*   ``timedelta`` / ``number``
556*   ``timedelta`` // ``int``
557
558
559``monthdelta``
560""""""""""""""
561
562``monthdelta`` returns an object that represents a timespan of a number of
563months. ``monthdelta`` allows zero or one arguments. With zero arguments
564``monthdelta`` returns the timespan for "0 months". In a boolean context this
565object is treated as false (i.e. ``bool(monthdelta()))`` or
566``bool(monthdelta(0)))`` return ``False``). The following arithmetic operations
567are supported::
568
569*   ``date`` + ``monthdelta``
570*   ``date`` - ``monthdelta``
571*   ``monthdelta`` + ``monthdelta``
572*   ``monthdelta`` - ``monthdelta``
573*   ``int`` * ``monthdelta``
574*   ``monthdelta`` // ``int``
575
576For operation involving ``date`` objects, if the resulting day falls out of the
577range of valid days for the target month, the last day for the target month
578will be used instead, i.e. ``<?print @(2000-01-31) + monthdelta(1)?>`` prints
579``2000-02-29 00:00:00``.
580
581
582``random``
583""""""""""
584
585``random()`` returns a random float value between 0 (included) and 1 (excluded).
586
587
588``randrange``
589"""""""""""""
590
591``randrange(start, stop, step)`` returns a random integer value between ``start``
592(included) and ``stop`` (excluded). ``step`` specifies the step size (i.e.
593when ``r`` is the random value, ``(r-start) % step`` will always be ``0``.
594``step`` and ``start`` can be ommitted.
595
596
597``randchoice``
598""""""""""""""
599
600``randchoice(seq)`` returns a random item from the sequence ``seq``.
601
602
603``isundefined``
604"""""""""""""""
605
606``isundefined(foo)`` returns ``True`` if ``foo`` is ``Undefined``, else
607``False`` is returned::
608
609    data is <?if isundefined(data)?>undefined<?else?>defined<?end if?>!
610
611
612``isdefined``
613"""""""""""""
614
615``isdefined(foo)`` returns ``False`` if ``foo`` is ``Undefined``, else
616``True`` is returned::
617
618    data is <?if isdefined(data)?>defined<?else?>undefined<?end if?>!
619
620
621``isnone``
622""""""""""
623
624``isnone(foo)`` returns ``True`` if ``foo`` is ``None``, else ``False`` is
625returned::
626
627    data is <?if isnone(data)?>None<?else?>something else<?end if?>!
628
629
630``isbool``
631""""""""""
632
633``isbool(foo)`` returns ``True`` if ``foo`` is ``True`` or ``False``, else
634``False`` is returned.
635
636
637``isint``
638"""""""""
639
640``isint(foo)`` returns ``True`` if ``foo`` is an integer object, else ``False``
641is returned.
642
643
644``isfloat``
645"""""""""""
646
647``isfloat(foo)`` returns ``True`` if ``foo`` is a float object, else ``False``
648is returned.
649
650
651``isstr``
652"""""""""
653
654``isstr(foo)`` returns ``True`` if ``foo`` is a string object, else ``False``
655is returned.
656
657
658``isdate``
659""""""""""
660
661``isdate(foo)`` returns ``True`` if ``foo`` is a date object, else ``False``
662is returned.
663
664
665``istimedelta``
666"""""""""""""""
667
668``istimedelta(foo)`` returns ``True`` if ``foo`` is a timedelta object, else
669``False`` is returned.
670
671
672``ismonthdelta``
673""""""""""""""""
674
675``ismonthdelta(foo)`` returns ``True`` if ``foo`` is a monthdelta object, else
676``False`` is returned.
677
678
679``islist``
680""""""""""
681
682``islist(foo)`` returns ``True`` if ``foo`` is a list object, else ``False``
683is returned.
684
685
686``isdict``
687""""""""""
688
689``isdict(foo)`` returns ``True`` if ``foo`` is a dictionary object, else
690``False`` is returned.
691
692
693``iscolor``
694"""""""""""
695
696``iscolor(foo)`` returns ``True`` if ``foo`` is a color object, else ``False``
697is returned.
698
699
700``istemplate``
701""""""""""""""
702
703``istemplate(foo)`` returns ``True`` if ``foo`` is a template object, else
704``False`` is returned.
705
706
707``bool``
708""""""""
709
710``bool(foo)`` converts ``foo`` to an boolean. I.e. ``True`` or ``False`` is
711returned according to the truth value of ``foo``. Calling ``bool`` without
712arguments returns ``False``.
713
714
715``int``
716"""""""
717
718``int(foo)`` converts ``foo`` to an integer. ``foo`` can be a string, a float,
719a boolean or an integer. ``int`` can also be called with two arguments. In this
720case the first argument must be a string and the second is the number base for
721the conversion. Calling ``int`` without arguments returns ``0``.
722
723
724``float``
725"""""""""
726
727``float(foo)`` converts ``foo`` to a float. ``foo`` can be a string, a float,
728a boolean or an integer. Calling ``float`` without arguments returns ``0.0``.
729
730
731``str``
732"""""""
733
734``str(foo)`` converts ``foo`` to a string. If ``foo`` is ``None`` or ``Undefined``
735the result will be the empty string. For lists and dictionaries the exact format
736is undefined, but should follow Python's repr format. For color objects the
737result is a CSS expression (e.g. ``"#fff"``). Calling ``str`` without arguments
738returns the empty string.
739
740
741``repr``
742""""""""
743
744``repr(foo)`` converts ``foo`` to a string representation that is useful for
745debugging proposes. The output looks that the UL constant that could be used to
746recreate the object.
747
748
749``asjson``
750""""""""""
751
752``asjson(foo)`` returns a JSON representation of the object ``foo``.
753(Date objects, color objects and templates are not supported by JSON, but
754``asjson`` will output the appropriate Javascript code for those objects)
755
756
757``fromjson``
758""""""""""""
759
760``fromjson(foo)`` decodes the JSON string ``foo`` and returns the resulting
761object. (Date objects, color objects and templates are not supported by
762``fromjson``).
763
764
765``asul4on``
766"""""""""""
767
768``asul4on(foo)`` returns the UL4ON representation of the object ``foo``.
769
770
771``fromul4on``
772"""""""""""""
773
774``fromul4on(foo)`` decodes the UL4ON string ``foo`` and returns the resulting
775object.
776
777
778``len``
779"""""""
780
781``len(foo)`` returns the length of a string, or the number of items in a list
782or dictionary.
783
784
785``any``
786"""""""
787
788``any(foo)`` returns ``True`` if any of the items in the iterable ``foo`` is
789true. Otherwise ``False`` is returns. If ``foo`` is empty ``False`` is returned.
790
791
792``all``
793"""""""
794
795``all(foo)`` returns ``True`` if all of the items in the iterable ``foo`` are
796true. Otherwise ``False`` is returns. If ``foo`` is empty ``True`` is returned.
797
798
799``enumerate``
800"""""""""""""
801
802Enumerates the items of the argument (which must be iterable, i.e. a string,
803a list or dictionary) and for each item in the original iterable returns a two
804item list containing the item position and the item itself. For example the
805following code::
806
807    <?for (i, c) in enumerate("foo")?>
808        (<?print c?>=<?print i?>)
809    <?end for?>
810
811prints::
812
813    (f=0)(o=1)(o=2)
814
815
816``isfirstlast``
817"""""""""""""""
818
819Iterates through items of the argument (which must be iterable, i.e. a string,
820a list or dictionary) and gives information about whether the item is the first
821and/or last in the iterable. For example the following code::
822
823    <?for (first, last, c) in isfirstlast("foo")?>
824        <?if first?>[<?end if?>
825        (<?print c?>)
826        <?if last?>]<?end if?>
827    <?end for?>
828
829prints::
830
831    [(f)(o)(o)]
832
833
834``isfirst``
835"""""""""""
836
837Iterates through items of the argument (which must be iterable, i.e. a string,
838a list or dictionary) and gives information about whether the item is the first
839in the iterable. For example the following code::
840
841    <?for (first, c) in isfirst("foo")?>
842        <?if first?>[<?end if?>
843        (<?print c?>)
844    <?end for?>
845
846prints::
847
848    [(f)(o)(o)
849
850
851``islast``
852""""""""""
853
854Iterates through items of the argument (which must be iterable, i.e. a string,
855a list or dictionary) and gives information about whether the item is the last
856in the iterable. For example the following code::
857
858    <?for (last, c) in islast("foo")?>
859        (<?print c?>)
860        <?if last?>]<?end if?>
861    <?end for?>
862
863prints::
864
865    (f)(o)(o)]
866
867
868``enumfl``
869""""""""""
870
871This function is a combination of ``enumerate`` and ``isfirstlast``. It iterates
872through items of the argument (which must be iterable, i.e. a string, a list
873or dictionary) and gives information about whether the item is the first
874and/or last in the iterable and its position. For example the following code::
875
876    <?for (index, first, last, c) in enumfl("foo")?>
877        <?if first?>[<?end if?>
878        (<?print c?>=<?print index?>)
879        <?if last?>]<?end if?>
880    <?end for?>
881
882prints::
883
884    [(f=0)(o=1)(o=2)]
885
886
887``xmlescape``
888"""""""""""""
889
890``xmlescape`` takes a string as an argument. It returns a new string where the
891characters ``&``, ``<``, ``>``, ``'`` and ``"`` have been replaced with the
892appropriate XML entity or character reference. For example::
893
894    <?print xmlescape("<'foo' & 'bar'>")?>
895
896prints::
897
898    ``&lt;&#39;foo&#39; &amp; ;&#39;bar&#39&gt;``
899
900If the argument is not a string, it will be converted to a string first.
901
902``<?printx foo?>`` is a shortcut for ``<?print xmlescape(foo)?>``.
903
904
905``min``
906"""""""
907
908``min`` returns the minimum value of its two or more arguments. If it's called
909with one argument, this argument must be iterable and ``min`` returns the
910minimum value of this argument.
911
912
913``max``
914"""""""
915
916``max`` returns the maximum value of its two or more arguments. If it's called
917with one argument, this argument must be iterable and ``max`` returns the
918maximum value of this argument.
919
920
921``sorted``
922""""""""""
923
924``sorted`` returns a sorted list with the items from its argument. For example::
925
926    <?for c in sorted('abracadabra')?><?print c?><?end for?>
927
928prints::
929
930    aaaaabbcdrr
931
932Supported arguments are iterable objects, i.e. strings, lists, dictionaries
933and colors.
934
935
936``chr``
937"""""""
938
939``chr(x)`` returns a one-character string containing the character with the
940codepoint ``x``. ``x`` must be an integer. For example ``<?print chr(0x61)?>``
941outputs ``a``.
942
943
944``ord``
945"""""""
946
947The argument for ``ord`` must be a one-character string. ``ord`` returns the
948codepoint of that character as an integer. For example ``<?print ord('a')?>``
949outputs ``97``.
950
951
952``hex``
953"""""""
954
955Return the hexadecimal representation of the integer argument (with a leading
956``0x``). For example ``<?print hex(42)?>`` outputs ``0x2a``.
957
958
959``oct``
960"""""""
961
962Return the octal representation of the integer argument (with a leading ``0o``).
963For example ``<?print oct(42)?>`` outputs ``0o52``.
964
965
966``bin``
967"""""""
968
969Return the binary representation of the integer argument (with a leading ``0b``).
970For example ``<?print bin(42)?>`` outputs ``0b101010``.
971
972
973``range``
974""""""""""
975
976``range`` returns an object that can be iterated and will produce consecutive
977integers up to the specified argument. With two arguments the first is the start
978value and the second is the stop value. With three arguments the third one is
979the step size (which can be negative). For example the following template::
980
981    <?for i in range(4, 10, 2)?>(<?print i?>)<?end for?>
982
983outputs::
984
985    (4)(6)(8)
986
987
988``type``
989""""""""
990
991``type`` returns the type of the object as a string. Possible return values are
992``"undefined"``, ``"none"``, ``"bool"``, ``"int"``, ``"float"``, ``"str"``,
993``"list"``, ``"dict"``, ``"date"``, ``"color"``, ``"template"`` and
994``"function"``. (If the type isn't recognized ``None`` is returned.)
995
996
997``rgb``
998"""""""
999
1000``rgb`` returns a color object. It can be called with
1001
1002*   three arguments, the red, green and blue values. The alpha value will be
1003    set to 255;
1004*   four arguments, the red, green, blue and alpha values.
1005
1006
1007``random``
1008""""""""""
1009
1010``random`` returns a random floating point number between 0 and 1.
1011
1012
1013``randchoice``
1014""""""""""""""
1015
1016``randchoice`` returns a random item from its argument (which must be list or
1017string)
1018
1019
1020``randchoice``
1021""""""""""""""
1022
1023``random`` returns a random item from its argument (which must be list or string).
1024
1025
1026Methods
1027-------
1028
1029Objects in :mod:`ll.ul4c` support some methods too (depending on the type of the
1030object).
1031
1032
1033``upper``
1034"""""""""
1035
1036The ``upper`` method of strings returns an uppercase version of the string for
1037which it's called::
1038
1039    <?print 'foo'.upper()?>
1040
1041prints::
1042
1043    FOO
1044
1045
1046``lower``
1047"""""""""
1048
1049The ``lower`` method of strings returns an lowercase version of the string for
1050which it's called.
1051
1052
1053``capitalize``
1054""""""""""""""
1055
1056The ``capitalize`` method of strings returns a copy of the string for with its
1057first letter capitalized.
1058
1059
1060``startswith``
1061""""""""""""""
1062
1063``x.startswith(y)`` returns ``True`` if the string ``x`` starts with the string
1064``y`` and ``False`` otherwise.
1065
1066
1067``endswith``
1068""""""""""""""
1069
1070``x.endswith(y)`` returns ``True`` if the string ``x`` ends with the string
1071``y`` and ``False`` otherwise.
1072
1073
1074``strip``
1075"""""""""
1076
1077The string method ``strip`` returns a copy of the string with leading and
1078trailing whitespace removed. If an argument ``chars`` is given and not ``None``,
1079characters in ``chars`` will be removed instead.
1080
1081
1082``lstrip``
1083""""""""""
1084
1085The string method ``lstrip`` returns a copy of the string with leading
1086whitespace removed. If an argument ``chars`` is given and not ``None``,
1087characters in ``chars`` will be removed instead.
1088
1089
1090``rstrip``
1091""""""""""
1092
1093The string method ``rstrip`` returns a copy of the string with trailing
1094whitespace removed. If an argument ``chars`` is given and not ``None``,
1095characters in ``chars`` will be removed instead.
1096
1097
1098``split``
1099"""""""""
1100The string method ``split`` splits the string into separate "words" and returns
1101the resulting list. Without any arguments, the string is split on whitespace
1102characters. With one argument the argument specifies the separator to use. The
1103second optional argument specifies the maximum number of splits to do.
1104
1105
1106``rsplit``
1107""""""""""
1108The string method ``rsplit`` works like ``split``, except that splitting starts
1109from the end (which is only relevant when the maximum number of splits is
1110given).
1111
1112
1113``find``
1114""""""""
1115
1116This method searches for a substring of the string or an item in a list
1117and returns the position of the first appearance of the substring/item or -1 if
1118the string/item can't be found. For example ``"foobar".find("bar")`` returns 3.
1119The optional second and third argument specify the start and end position for
1120the search.
1121
1122
1123``rfind``
1124"""""""""
1125
1126This method works like ``find`` but searches from the end.
1127
1128
1129``replace``
1130"""""""""""
1131
1132The string method ``replace`` has two arguments. It returns a new string where
1133each occurrence of the first argument is replaced by the second argument, i.e.
1134``"abracadabra".replace("ab", "ba")`` returns ``"baracadbara"``
1135
1136
1137``get``
1138"""""""
1139
1140``get`` is a dictionary method. ``d.get(k, v)`` returns ``d[k]`` if the key
1141``k`` is in ``d``, else ``v`` is returned. If ``v`` is not given, it defaults
1142to ``None``.
1143
1144
1145``join``
1146""""""""
1147
1148``join`` is a string method. It returns a concatentation of the strings in the
1149argument sequence with the string itself as the separator, i.e.::
1150
1151    <?print "+".join("1234")?>
1152
1153outputs::
1154
1155    1+2+3+4
1156
1157
1158``renders``
1159"""""""""""
1160
1161The ``renders`` method of template objects renders the template and returns the
1162output as a string. The parameter can be passed via keyword argument or via the
1163``**`` syntax::
1164
1165    <?code output = template.renders(a=17, b=23)?>
1166    <?code data = {'a': 17, 'b': 23)?>
1167    <?code output = template.renders(**data)?>
1168
1169
1170``isoformat``
1171"""""""""""""
1172
1173``isoformat`` is a date method. It returns the date object in ISO 8601 format,
1174i.e.::
1175
1176    <?print now().isoformat()?>
1177
1178might output::
1179
1180    2010-02-22T18:30:29.569639
1181
1182
1183``mimeformat``
1184""""""""""""""
1185
1186``mimeformat`` is a date method. It returns the date object in MIME format
1187(assuming the date object is in UTC), i.e.::
1188
1189    <?print utcnow().mimeformat()?>
1190
1191might output::
1192
1193    Mon, 22 Feb 2010 17:38:40 GMT
1194
1195
1196``day``, ``month``, ``year``, ``hour``, ``minute``, ``second``, ``microsecond``, ``weekday``
1197""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1198
1199Those methods are date methods. They return a specific attribute of a date
1200object. For example the following reproduces the ``mimeformat`` output from
1201above (except for the linefeeds of course)::
1202
1203    <?code weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']?>
1204    <?code months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']?>
1205    <?code t = @(2010-02-22T17:38:40.123456)?>
1206    <?print weekdays[t.weekday()]?>,
1207    <?print format(t.day(), '02')?>
1208    <?print months[t.month()-1]?>
1209    <?print format(t.year(), '04')?>
1210    <?print format(t.hour(), '02')?>:
1211    <?print format(t.minute(), '02')?>:
1212    <?print format(t.second(), '02')?>.
1213    <?print format(t.microsecond(), '06')?> GMT
1214
1215
1216``week``
1217""""""""
1218
1219``week`` is a date method. This method returns the week number of the year.
1220It supports one argument: the weekday number that should be considered the start
1221day of the week (0 for Monday, ... 6 for Sunday). All days in a new year
1222preceding the first week start day are considered to be in week 0. The week
1223start day defaults to 0 (Monday).
1224
1225
1226``yearday``
1227"""""""""""
1228
1229``yearday`` is a date method. It returns the number of days since the beginning
1230of the year, so::
1231
1232    <?print @(2010-01-01).yearday()?>
1233
1234prints ``1`` and::
1235
1236    <?print @(2010-12-31).yearday()?>
1237
1238prints ``365``.
1239
1240
1241Templates as functions
1242======================
1243
1244UL4 templates can be used as functions too. Calling a template as a function
1245will ignore any output from the template. The return value will be the value of
1246the first ``<?return?>`` tag::
1247
1248    from ll import ul4c
1249
1250    code = '''
1251        <?for item in data?>
1252            <?if "i" in item?>
1253                <?return item?>
1254            <?end if?>
1255        <?end for?>
1256    '''
1257
1258    function = ul4c.Function(code)
1259
1260    output = function(data=["Python", "Java", "Javascript", "PHP"]))
1261
1262With this, ``output`` will be the string ``"Javascript"``.
1263
1264
1265When no ``<?return?>`` tag is encountered, ``None`` will be returned.
1266
1267
1268Delimiters
1269==========
1270
1271It is possible to specify alternative delimiters from the template tags::
1272
1273    >>> from ll import ul4c
1274    >>> t = ul4c.Template(
1275    ...     "{{for i in range(10)}}{{print i}};{{end for}}",
1276    ...     startdelim="{{",
1277    ...     enddelim="}}"
1278    ... )
1279    >>> t.renders()
1280    '0;1;2;3;4;5;6;7;8;9;'
1281
1282
1283Whitespace
1284==========
1285
1286Normally the literal text between template tags will be output as it is. However
1287it is possible to specify that linefeeds and the following indentation should be
1288ignored. This is done with the parameter ``keepws``::
1289
1290    >>> from ll import ul4c
1291    >>> t = ul4c.Template("""
1292    ...     <?for i in range(10)?>
1293    ...         <?print i?>
1294    ...         ;
1295    ...     <?end for?>
1296    ... """, keepws=False)
1297    >>> t.renders()
1298    '0;1;2;3;4;5;6;7;8;9;'
1299
1300Using ``keepws=True`` (the default) the output would include all the line feeds
1301and whitespace::
1302
1303    '\n\t\n\t\t0\n\t\t;\n\t\n\t\t1\n\t\t;\n\t\n\t\t2...
Note: See TracBrowser for help on using the browser.