Skip to content
Myr

objects.txt

This file

Path

docs/src/objects.txt

128 lines · 4.1 KiB

Last changed by

[svn] implemented and documented jinja streaming interfaceArmin Ronacherbefore adoption02d81f7

History of this file

Take it

1==============2Global objects3==============45This section covers the behavior of global objects in the Jinja namespace and6also the behavior of their attributes.78Functions9=========1011`Filters`_ and `Tests`_ are special kind of functions you cannot call without12and argument. Global functions are different. Those are really just ordinary13python functions. You can register them on the global namespace easily:1415.. sourcecode:: python1617    def my_function():18        return [1, 2, 3]1920    env.globals['my_function'] = my_function2122In the template you can not call it like this:2324.. sourcecode:: jinja2526    {{ my_function() }}2728Of couse you can pass any argument to it. But what if you want to access the29context or environment? In that case you have to decorate a function or mark30it (both work exactly the same, but the decorator way is probably nicer if you31have python >= 2.4):3233.. sourcecode:: python3435    from cgi import escape36    from pprint import pformat37    from jinja.datastructure import contextcallable3839    @contextcallable40    def printcontext(env, context):41        result = []42        for key, value in context.to_dict():43            result.append('<tr><th>%s</th><td>%r</td></tr>' %44                          (escape(unicode(key)), escape(pformat(value))))45        return '<table>%s</table>' % u'\n'.join(result)4647If this function is registered in the environment namespace then and called48from the template it should return the content of the context as simple html49template. Of course you can modify the context too. For more informations about50the context object have a look at the `context object`_ documentation.5152Deferred Values53===============5455You can pass functions to the template that are called to provide values at56first access. Say you want to pass the list of recently written comments to57all templates. But not necessarily every template will render that. In that58situation you can create a function that returns that value and wrap it in an59`Deferred` object. The first time a template accesses the variable then the60`Deferred` object is resolved:6162.. sourcecode:: python6364    from jinja.datastructure import Deferred65    from yourapplication.models import Comments6667    def get_recent_comments(env, context, name):68        # do what ever you want here.69        return Comments.get_recent(10)7071    env.globals['recent_comments'] = Deferred(get_recent_comments)7273The function is always called with the same arguments. The first one is the74current environment, the second the context and the third is the name of the75variable. In this example ``recent_comments``.7677Unsafe Methods / Attributes78===========================7980Because Jinja is sandboxed it provides several ways to prevent unsafe attribute81access. You can mark both attributes and methods as unsafe:8283.. sourcecode:: python8485    from jinja.datastructure import unsafe8687    class MyModel(...):8889        # just give access to a and b. Default is all90        # note that this also disallows the functions from below.91        # if you use jinja_allowed_attributes you don't have to92        # do the code below because methods are threaded as attributes93        # too.94        jinja_allowed_attributes = ['a', 'b']9596        def __init__(self, ...):97            ...98            self.a = ...99            self.b = ...100101        # python2.4 way of marking methods102        @unsafe103        def save(self):104            """Save the model."""105106        # python2.3 way for the same107        def delete(self):108            """Delete the model."""109        delete.jinja_unsafe_call = True110111112Bypassing Automatic Filtering113=============================114115With Jinja 1.1 it's possible to assign filters to any variable printed. Of116course there are ways to bypass that in order to make sure an object does117not get escaped etc.118119In order to disable automatic filtering for an object you have to make120sure that it's either an subclass of `unicode` or implements a121`__unicode__` method. `__str__` will work too as long as the return value122only contains ASCII values. Additionally you have to add an attribute to123that object named `jinja_no_finalization` and set that to `True`.124125126.. _Filters: filters.txt127.. _Tests: tests.txt128.. _context object: contextenv.txt