File: filter-dev.txt

package info (click to toggle)
jinja 0.9-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 412 kB
  • ctags: 485
  • sloc: python: 2,551; makefile: 40
file content (64 lines) | stat: -rw-r--r-- 2,164 bytes parent folder | download
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
============
Filter Howto
============

You can easily add your own filters to the Jinja filter system.

Filters are just Python functions that takes at least on arguments, the value
of the variable (input) -- not necessarily a string.

And additonally an unlimted number of arguments -- these can have a default
value.

For example in the filter ``{{ var | foobar "spam", "eggs" }}`` the filter
``foobar`` would be passed the variables ``spam`` and ``eggs`` als the
arguments.

Filter functions should always return something. They shouldn't raise
exceptions. They should fail silently. In case of error, they should return
either the original input or an empty string -- whichever makes more sense.

Here is an example for a small string filter definition::

    from jinja.filters import stringfilter

    def handle_ljust(s, width):
        if not isinstance(s, basestring):
            s = str(s)
        return s.ljust(width)
    handle_jlust = stringfilter(handle_ljust)

The decorator helps you to automagically do some charset related manipulation
on the input data. If you don't work on string data you have to do that on
your own. Here a normal definition::

    def do_sum(iterable, context, max=None):
        res = sum(iterable)
        if not max is None and res > max:
            res = max
        return unicode(res)

When you've written your filter definition you have to register it in
the standard library::

    from jinja.library import stdlib
    stdlib.register_filter('ljust', handle_ljust)
    stdlib.register_filter('sum', handle_sum)

If you want your own lib to not affect the default library you can use the
``clone`` method::

    from jinja.library import stdlib
    mylib = stdlib.clone()
    mylib.register_filter('ljust', handle_ljust)
    mylib.register_filter('sum', handle_sum)

The constructor of the ``Template`` class takes a ``lib`` tag for defining
the library the template should use.

All you have to do is to ensure that the module gets loaded before Jinja starts
the rendering process. Then the filter ``ljust`` will be available in the list
of known filters::

    This is a small quote:
    {{ quote | ljust 10 }}