[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
Provenance
- Commit
94dd3d0- Tree
2eef0bb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
934cb71
5 files changed+260 added−1 removed
added:docs/src/contextenv.txt+136 added
1+=======================2+Context and Environment3+=======================4+5+The two central objects in Jinja are the `Environment` and `Context`. Both6+are designed to be subclassed by applications if they need to extend Jinja.7+8+Environment9+===========10+11+The initialization parameters are already covered in the `Quickstart`_ thus12+not repeated here.13+14+But beside those configurable instance variables there are some functions used15+in the template evaluation code you may want to override:16+17+**def** `to_unicode` *(self, value)*:18+19+ 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.22+23+ Also `None` is converted into an empty string per default.24+25+**def** `get_translator` *(self, context)*:26+27+ 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`_.32+33+ If you don't provide a translator a default one is used to switch34+ between singular and plural forms.35+36+**def** `apply_filters` *(self, value, context, filters)*:37+38+ 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:43+44+ .. sourcecode:: python45+46+ [('escape', ()), ('replace', (u'a', u'b'))]47+48+ 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.52+53+**def** `perform_test` *(self, context, testname, args, value, invert)*:54+55+ Like `apply_filters` you usually don't override this one. It's the56+ callback function for tests (``foo is bar`` / ``foo is not bar``).57+58+ 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.62+63+ Missing tests should raise a `TestNotFound` exception.64+65+**def** `get_attribute` *(self, obj, attributes)*:66+67+ Get `attributes` from the object provided. The default implementation68+ performs security tests for each attribute.69+70+**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.76+77+ The default implementation performs some security checks.78+79+**def** `call_function_simple` *(self, f, context)*:80+81+ Like `call_function` but without arguments.82+83+**def** `finish_var` *(self, value)*:84+85+ Postprocess a variable before it's sent to the template.86+ 87+.. admonition:: Note88+89+ The Enviornment class is defined in `jinja.environment.Environment`90+ but imported into the `jinja` package because it's often used.91+92+Context93+=======94+95+Jinja wraps the variables passed to the template in a special class called a96+context. This context supports variables on multiple layers and lazy (deferred)97+objects. Often your application has a request object, database connection98+object or something similar you want to access in filters, functions etc.99+100+Beacause of that you can easily subclass a context to add additional variables101+or to change the way it behaves.102+103+**def** `pop` *(self)*:104+105+ Pop the outermost layer and return it.106+107+**def** `push` *(self, data=None)*:108+109+ Push a dict to the stack or an empty layer.110+111+ Has to return the pushed object.112+113+**def** `to_dict` *(self)*:114+115+ Flatten the context and convert it into a dict.116+117+**def** `__getitem__` *(self, name)*:118+119+ Resolve an item. Per default this also resolves `Deferred` objects.120+121+**def** `__setitem__` *(self, name, value)*:122+123+ Set an item in the outermost layer.124+125+**def** `__delitem__` *(self, name)*:126+127+ Delete an item in the outermost layer. Do not raise exceptions if128+ the value does not exist.129+130+**def** `__contains__` *(self, name)*:131+132+ Return `True` if `name` exists in the context.133+134+135+.. _Quickstart: devintro.txt136+.. _gettext documentation: http://docs.python.org/lib/module-gettext.htmlmodified:docs/src/devintro.txt+3 added
58 unmodified lines59 `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 ========================= ==================================================66 67 All of these variables except those marked with a star (*) are modifiable after68 environment initialization.65 unmodified lines134 Writing tests is explained in the `test development`_ section.135 136 137 .. _installation: installation.txt138+.. _context documentation: contextenv.txt139 .. _translators: translators.txt140 .. _loader: loaders.txt141 .. _filter development: filters.txt142 .. _test development: tests.txtmodified:docs/src/index.txt+4 added
14 unmodified lines15 - `Filter Functions <filters.txt>`_16 17 - `Test Functions <tests.txt>`_18 19+ - `Global Objects <objects.txt>`_20+21+ - `Context and Environment <contextenv.txt>`_22+23 - `Translators <translators.txt>`_24 25 - `Framework Integration <frameworks.txt>`_26 7 unmodified linesadded:docs/src/objects.txt+110 added
1+==============2+Global objects3+==============4+5+This section covers the behavior of global objects in the Jinja namespace and6+also the behavior of their attributes.7+8+Functions9+=========10+11+`Filters`_ and `Tests`_ are special kind of functions you cannot call without12+and argument. Global functions are different. Those are really just ordinary13+python functions. You can register them on the global namespace easily:14+15+.. sourcecode:: python16+17+ def my_function():18+ return [1, 2, 3]19+20+ env.globals['my_function'] = my_function21+22+In the template you can not call it like this:23+24+.. sourcecode:: jinja25+26+ {{ my_function() }}27+28+Of couse you can pass any argument to it. But what if you want to access the29+context or environment? In that case you have to decorate a function or mark30+it (both work exactly the same, but the decorator way is probably nicer if you31+have python >= 2.4):32+33+.. sourcecode:: python34+35+ from cgi import escape36+ from pprint import pformat37+ from jinja.datastructure import contextcallable38+39+ @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)46+47+If this function is registered in the environment namespace then and called48+from the template it should return the content of the context as simple html49+template. Of course you can modify the context too. For more informations about50+the context object have a look at the `context object`_ documentation.51+52+Deferred Values53+===============54+55+You can pass functions to the template that are called to provide values at56+first access. Say you want to pass the list of recently written comments to57+all templates. But not necessarily every template will render that. In that58+situation 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:61+62+.. sourcecode:: python63+64+ from jinja.datastructure import Deferred65+ from yourapplication.models import Comments66+67+ def get_recent_comments(env, context, name):68+ # do what ever you want here.69+ return Comments.get_recent(10)70+71+ env.globals['recent_comments'] = Deferred(get_recent_comments)72+73+The function is always called with the same arguments. The first one is the74+current environment, the second the context and the third is the name of the75+variable. In this example ``recent_comments``.76+77+Unsafe Methods / Attributes78+===========================79+80+Because Jinja is sandboxed it provides several ways to prevent unsafe attribute81+access. You can mark both attributes and methods as unsafe:82+83+.. sourcecode:: python84+85+ from jinja.datastructure import unsafe86+87+ class MyModel(...):88+89+ # just give access to a and b. Default is all90+ jinja_allowed_attributes = ['a', 'b']91+92+ def __init__(self, ...):93+ ...94+ self.a = ...95+ self.b = ...96+97+ # python2.4 way of marking methods98+ @unsafe99+ def save(self):100+ """Save the model."""101+102+ # python2.3 way for the same103+ def delete(self):104+ """Delete the model."""105+ delete.jinja_unsafe_call = True106+107+108+.. _Filters: filters.txt109+.. _Tests: tests.txt110+.. _context object: contextenv.txtmodified:jinja/datastructure.py+7 added-1 removed
115 unmodified lines116 def __init__(self, factory):117 self.factory = factory118 119 def __call__(self, context, name):120- return self.factory(context, name)120+ return self.factory(context.environment, context, name)121 122 123 class Markup(unicode):124 """66 unmodified lines191 def __delitem__(self, name):192 if name in self.current:193 del self.current[name]194 195+ def __contains__(self, name):196+ for layer in self._stack:197+ if name in layer:198+ return True199+ return False200+201 def __repr__(self):202 tmp = {}203 for d in self._stack:204 for key, value in d.iteritems():166 unmodified lines