Skip to content
Myr

api.txt

This file

Path

docs/src/api.txt

315 lines · 10.9 KiB

Last changed by

[svn] many jinja changes:Armin Ronacherbefore adoptionfb5bebc

History of this file

Take it

[svn] many jinja changes:Armin Ronacherbefore adoptionfb5bebc

lines 1–315why, one step back
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** `parse` *(source, filename)*:1819 Parse the sourcecode and return the abstract syntax tree. This tree of20 nodes is used by the `translators`_ to convert the template into21 executable source- or bytecode.2223**def** `lex` *(source, filename)*:2425 Tokenize the given sourcecode and return a generator of tuples in the26 form ``(lineno, token, value)``. The filename is just used in the27 exceptions raised.28 29 **New in Jinja 1.1**3031**def** `from_string` *(source)*:3233 Load and parse a template source and translate it into eval-able Python34 code. This code is wrapped within a `Template` class that allows you to35 render it.3637**def** `get_template` *(name)*:3839 Load a template from a loader. If the template does not exist, you will40 get a `jinja.exceptions.TemplateNotFound` exception.4142**def** `to_unicode` *(self, value)*:4344 Called to convert variables to unicode. Per default this checks if the45 value is already unicode. If not it's converted to unicode using the46 charset defined on the environment.4748 Also `None` is converted into an empty string per default.4950**def** `get_translator` *(self, context)*:5152 Return the translator used for i18n. A translator is an object that53 provides the two functions ``gettext(string)`` and54 ``ngettext(singular, plural, n)``. Both of those functions have to55 behave like the `ugettext` and `nugettext` functions described in the56 python `gettext documentation`_.5758 If you don't provide a translator a default one is used to switch59 between singular and plural forms.6061 Have a look at the `i18n`_ section for more information.6263**def** `get_translations` *(self, name)*:6465 Get the translations for the template `name`. Only works if a loader66 is present. See the `i18n`_ section for more details.6768**def** `get_translations_for_string` *(self, string)*:6970 Get the translations for the string `string`. This works also if no71 loader is present and can be used to lookup translation strings from72 templates that are loaded from dynamic resources like databases.7374**def** `apply_filters` *(self, value, context, filters)*:7576 Now this function is a bit tricky and you usually don't have to override77 it. It's used to apply filters on a value. The Jinja expression78 ``{{ foo|escape|replace('a', 'b') }}`` calls the function with the79 value of `foo` as first parameter, the current context as second and80 a list of filters as third. The list looks like this:8182 .. sourcecode:: python8384 [('escape', ()), ('replace', (u'a', u'b'))]8586 As you can see the filter `escape` is called without arguments whereas87 `replace` is called with the two literal strings ``a`` and ``b``, both88 unicode. The filters for the names are stored on ``self.filters`` in a89 dict. Missing filters should raise a `FilterNotFound` exception.9091 **Warning** this is a Jinja internal method. The actual implementation92 and function signature might change.9394**def** `perform_test` *(self, context, testname, args, value, invert)*:9596 Like `apply_filters` you usually don't override this one. It's the97 callback function for tests (``foo is bar`` / ``foo is not bar``).9899 The first parameter is the current contex, the second the name of100 the test to perform. the third a tuple of arguments, the fourth is101 the value to test. The last one is `True` if the test was performed102 with the `is not` operator, `False` if with the `is` operator.103104 Missing tests should raise a `TestNotFound` exception.105106 **Warning** this is a Jinja internal method. The actual implementation107 and function signature might change.108109**def** `get_attribute` *(self, obj, attribute)*:110111 Get `attribute` from the object provided. The default implementation112 performs security tests.113114 **Warning** this is a Jinja internal method. The actual implementation115 and function signature might change.116117**def** `get_attributes` *(self, obj, attributes)*:118119 Get some attributes from the object. If `attributes` is an empty120 sequence the object itself is returned unchanged.121122**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:123 124 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and125 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`126 is not `None` you have to add it to the arguments, if `dyn_kwargs` is127 not `None` you have to update the `kwargs` with it.128129 The default implementation performs some security checks.130131 **Warning** this is a Jinja internal method. The actual implementation132 and function signature might change.133134**def** `call_function_simple` *(self, f, context)*:135136 Like `call_function` but without arguments.137138 **Warning** this is a Jinja internal method. The actual implementation139 and function signature might change.140141**def** `finish_var` *(self, value, ctx)*:142143 Postprocess a variable before it's sent to the template.144145 **Warning** this is a Jinja internal method. The actual implementation146 and function signature might change.147 148.. admonition:: Note149150 The Enviornment class is defined in `jinja.environment.Environment`151 but imported into the `jinja` package because it's often used.152153Context154=======155156Jinja wraps the variables passed to the template in a special class called a157context. This context supports variables on multiple layers and lazy (deferred)158objects. Often your application has a request object, database connection159object or something similar you want to access in filters, functions etc.160161The default context object is defined in `jinja.datastructure`. If you want162to provide your own context object always subclass the default one. This163ensures that the class continues working after Jinja upgrades.164165Beacause of that you can easily subclass a context to add additional variables166or to change the way it behaves.167168**def** `pop` *(self)*:169170 Pop the outermost layer and return it.171172**def** `push` *(self, data=None)*:173174 Push a dict to the stack or an empty layer.175176 Has to return the pushed object.177178**def** `to_dict` *(self)*:179180 Flatten the context and convert it into a dict.181182**def** `__getitem__` *(self, name)*:183184 Resolve an item. Per default this also resolves `Deferred` objects.185186**def** `__setitem__` *(self, name, value)*:187188 Set an item in the outermost layer.189190**def** `__delitem__` *(self, name)*:191192 Delete an item in the outermost layer. Do not raise exceptions if193 the value does not exist.194195**def** `__contains__` *(self, name)*:196197 Return `True` if `name` exists in the context.198199**attribute** `cache`:200201 The cache is a dict which can be used by filters, test functions202 and global objects to cache data. It's also used by the environment203 to cache often used tests and filters.204205**attribute** `translate_func`:206207 This property is created on first access and returns a translation208 function used by the rendering process to translate strings with the209 translator defined on the environment.210211.. admonition:: Note212213 The context uses a stack of dicts internally to represent the214 layers of variables. It contains at least 3 levels available on215 the context with some attributes. Those are:216217 `globals`:218 219 The reference to the global namespace of the environment.220 It's the lowest namespace on the stack and thus immutable221222 `initial`:223224 The initial namespace. Contains the values passed to the225 context in the render function. It also contains the resolved226 deferred values for bot the `initial` and the `globals`227 namespace.228229 `current`:230231 The reference to the current active namespace. When the232 context is initialized this automatically points to an233 empty namespace.234235 The number of layers on the stack are theoretically unlimited.236 Some elements in the template language like loops, blocks,237 macros and others push and pop the layer on entering and leaving238 the section.239240 This is done in order to keep the namespace clean.241242 Note that since Jinja 1.1 the context object is a subclass of the243 `BaseContext`, a much simpler class that just implements a stack244 like namespace for python. If the `_speedups` extension was245 compiled for jinja the base class will be246 `jinja._speedups.BaseContext` otherwise `jinja._native.BaseContext`.247248 Since you cannot reproduce completely the same semantics in python249 and the C API there are some things you should keep in mind:250251 - The `stack` attribute of the context maps to the real layers252 on the stack, thus you can modify the items but the list as253 such is meant to be read only.254255 - `globals`, `current` and `initial` are read only attributes that256 map to layers on the stack which you can of course modify.257258259Exceptions260==========261262During parsing and evaluation Jinja raises a couple of Jinja specific263exceptions. All of those exceptions are defined in the `jinja.exceptions`264module and are subclasses of the `TemplateError` class defined there.265266Here a list of exceptions that could occur:267268`SecurityException`:269270 An exception that is raised if the template tried to access something271 it should not access. In the default configuration this exception272 will get caught in the Jinja rendering process and silenced.273274 If however the environment is configured to not silently fail it275 could happen that this exception reaches the application.276277`FilterNotFound`:278279 Raised if the template tried to apply a filter that does not exist.280 Since this exception is a subclass of `KeyError` too you can catch281 it this way too.282283`FilterArgumentError`:284285 Raised if the filter received an argument that it couldn't handle.286 It's a subclass of `TypeError` too so you can catch it this way too.287288`TestNotFound`:289290 Raised if the template tried to perform a test that does not exist.291 Since this exception is a subclass of `KeyError` too you can catch292 it this way too.293294`TestArgumentError`:295296 Raised if a test function received an argument that it couldn't handle.297 It's a subclass of `TypeError` too so you can catch it this way too.298299`TemplateNotFound`:300301 Raised if a template does not exist. Subclass of `IOError` too.302303`TemplateSyntaxError`:304305 Subclass of `SyntaxError` and used to indicate an syntax error.306307`TemplateRuntimeError`:308309 Generic runtime error exception which can occour at various places.310311312.. _i18n: i18n.txt313.. _translators: translators.txt314.. _Quickstart: devintro.txt315.. _gettext documentation: http://docs.python.org/lib/module-gettext.html