Skip to content
Myr

[svn] again doc updates

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 934cb71 · Browse files · 5 files+260 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+260 added−1 removed

  • other:+260 added−1 removed

5 files+260 added−1 removed

added:docs/src/contextenv.txt+136 added
1=======================2Context and Environment3=======================45The two central objects in Jinja are the `Environment` and `Context`. Both6are designed to be subclassed by applications if they need to extend Jinja.78Environment9===========1011The initialization parameters are already covered in the `Quickstart`_ thus12not repeated here.1314But beside those configurable instance variables there are some functions used15in the template evaluation code you may want to override:1617**def** `to_unicode` *(self, value)*:1819 Called to convert variables to unicode. Per default this checks if the20 value is already unicode. If not it's converted to unicode using the21 charset defined on the environment.2223 Also `None` is converted into an empty string per default.2425**def** `get_translator` *(self, context)*:2627 Return the translator used for i18n. A translator is an object that28 provides the two functions ``gettext(string)`` and29 ``ngettext(singular, plural, n)``. Both of those functions have to30 behave like the `ugettext` and `nugettext` functions described in the31 python `gettext documentation`_.3233 If you don't provide a translator a default one is used to switch34 between singular and plural forms.3536**def** `apply_filters` *(self, value, context, filters)*:3738 Now this function is a bit tricky and you usually don't have to override39 it. It's used to apply filters on a value. The Jinja expression40 ``{{ foo|escape|replace('a', 'b') }}`` calls the function with the41 value of `foo` as first parameter, the current context as second and42 a list of filters as third. The list looks like this:4344 .. sourcecode:: python4546 [('escape', ()), ('replace', (u'a', u'b'))]4748 As you can see the filter `escape` is called without arguments whereas49 `replace` is called with the two literal strings ``a`` and ``b``, both50 unicode. The filters for the names are stored on ``self.filters`` in a51 dict. Missing filters should raise a `FilterNotFound` exception.5253**def** `perform_test` *(self, context, testname, args, value, invert)*:5455 Like `apply_filters` you usually don't override this one. It's the56 callback function for tests (``foo is bar`` / ``foo is not bar``).5758 The first parameter is the current contex, the second the name of59 the test to perform. the third a tuple of arguments, the fourth is60 the value to test. The last one is `True` if the test was performed61 with the `is not` operator, `False` if with the `is` operator.6263 Missing tests should raise a `TestNotFound` exception.6465**def** `get_attribute` *(self, obj, attributes)*:6667 Get `attributes` from the object provided. The default implementation68 performs security tests for each attribute.6970**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:71 72 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and73 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`74 is not `None` you have to add it to the arguments, if `dyn_kwargs` is75 not `None` you have to update the `kwargs` with it.7677 The default implementation performs some security checks.7879**def** `call_function_simple` *(self, f, context)*:8081 Like `call_function` but without arguments.8283**def** `finish_var` *(self, value)*:8485 Postprocess a variable before it's sent to the template.86 87.. admonition:: Note8889 The Enviornment class is defined in `jinja.environment.Environment`90 but imported into the `jinja` package because it's often used.9192Context93=======9495Jinja wraps the variables passed to the template in a special class called a96context. This context supports variables on multiple layers and lazy (deferred)97objects. Often your application has a request object, database connection98object or something similar you want to access in filters, functions etc.99100Beacause of that you can easily subclass a context to add additional variables101or to change the way it behaves.102103**def** `pop` *(self)*:104105 Pop the outermost layer and return it.106107**def** `push` *(self, data=None)*:108109 Push a dict to the stack or an empty layer.110111 Has to return the pushed object.112113**def** `to_dict` *(self)*:114115 Flatten the context and convert it into a dict.116117**def** `__getitem__` *(self, name)*:118119 Resolve an item. Per default this also resolves `Deferred` objects.120121**def** `__setitem__` *(self, name, value)*:122123 Set an item in the outermost layer.124125**def** `__delitem__` *(self, name)*:126127 Delete an item in the outermost layer. Do not raise exceptions if128 the value does not exist.129130**def** `__contains__` *(self, name)*:131132 Return `True` if `name` exists in the context.133134135.. _Quickstart: devintro.txt136.. _gettext documentation: http://docs.python.org/lib/module-gettext.html
modified:docs/src/devintro.txt+3 added
58 unmodified lines
59`loader` Specify a template loader.60`filters` dict of filters or the default filters if not61 defined.62`tests` dict of tests of the default tests if not defined.63`context_class` the context class this template should use. See64 the `context documentation`_ for more details.65========================= ==================================================6667All of these variables except those marked with a star (*) are modifiable after68environment initialization.
65 unmodified lines
134Writing tests is explained in the `test development`_ section.135136137.. _installation: installation.txt138.. _context documentation: contextenv.txt139.. _translators: translators.txt140.. _loader: loaders.txt141.. _filter development: filters.txt142.. _test development: tests.txt
modified:docs/src/index.txt+4 added
14 unmodified lines
15 - `Filter Functions <filters.txt>`_1617 - `Test Functions <tests.txt>`_1819 - `Global Objects <objects.txt>`_2021 - `Context and Environment <contextenv.txt>`_2223 - `Translators <translators.txt>`_2425 - `Framework Integration <frameworks.txt>`_26
7 unmodified lines
added:docs/src/objects.txt+110 added
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 jinja_allowed_attributes = ['a', 'b']9192 def __init__(self, ...):93 ...94 self.a = ...95 self.b = ...9697 # python2.4 way of marking methods98 @unsafe99 def save(self):100 """Save the model."""101102 # python2.3 way for the same103 def delete(self):104 """Delete the model."""105 delete.jinja_unsafe_call = True106107108.. _Filters: filters.txt109.. _Tests: tests.txt110.. _context object: contextenv.txt
modified:jinja/datastructure.py+7 added-1 removed
115 unmodified lines
116 def __init__(self, factory):117 self.factory = factory118119 def __call__(self, context, name):120 return self.factory(context, name)120 return self.factory(context.environment, context, name)121122123class Markup(unicode):124 """
66 unmodified lines
191 def __delitem__(self, name):192 if name in self.current:193 del self.current[name]194195 def __contains__(self, name):196 for layer in self._stack:197 if name in layer:198 return True199 return False200201 def __repr__(self):202 tmp = {}203 for d in self._stack:204 for key, value in d.iteritems():
166 unmodified lines