api.rst
This file
Path
docs/api.rst
787 lines · 26.8 KiB
Last changed by
three is the new twoArmin Ronacherbefore adoption2e3c9c7
History of this fileTake it
The walk stopped after 200 commits: lines older than 9a0078d point at it.
Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 1–16why, one step back1API2===34.. module:: jinja25 :synopsis: public Jinja2 API67This document describes the API to Jinja2 and not the template language. It8will be most useful as reference to those implementing the template interface9to the application and not those who are creating Jinja2 templates.1011Basics12------1314Jinja2 uses a central object called the template :class:`Environment`.15Instances of this class are used to store the configuration, global objects16and are used to load templates from the file system or other locations.Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58
line 17why, one step back17Even if you are creating templates from strings by using the constructor ofRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 18–54why, one step back18:class:`Template` class, an environment is created automatically for you,19albeit a shared one.2021Most applications will create one :class:`Environment` object on application22initialization and use that to load templates. In some cases it's however23useful to have multiple environments side by side, if different configurations24are in use.2526The simplest way to configure Jinja2 to load templates for your application27looks roughly like this::2829 from jinja2 import Environment, PackageLoader30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))3132This will create a template environment with the default settings and a33loader that looks up the templates in the `templates` folder inside the34`yourapplication` python package. Different loaders are available35and you can also write your own if you want to load templates from a36database or other resources.3738To load a template from this environment you just have to call the39:meth:`get_template` method which then returns the loaded :class:`Template`::4041 template = env.get_template('mytemplate.html')4243To render it with some variables, just call the :meth:`render` method::4445 print template.render(the='variables', go='here')4647Using a template loader rather then passing strings to :class:`Template`48or :meth:`Environment.from_string` has multiple advantages. Besides being49a lot easier to use it also enables template inheritance.505152Unicode53-------54Some tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 55why, one step back55Jinja2 is using Unicode internally which means that you have to pass UnicodeRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 56–63why, one step back56objects to the render function or bytestrings that only consist of ASCII57characters. Additionally newlines are normalized to one end of line58sequence which is per default UNIX style (``\n``).5960Python 2.x supports two ways of representing string objects. One is the61`str` type and the other is the `unicode` type, both of which extend a type62called `basestring`. Unfortunately the default is `str` which should not63be used to store text based information unless only ASCII characters areApplied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58
line 64why, one step back64used. With Python 2.6 it is possible to make `unicode` the default on a perRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 65–66why, one step back65module level and with Python 3 it will be the default.66Some tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 67why, one step back67To explicitly use a Unicode string you have to prefix the string literalRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 68why, one step back68with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python willSome tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 69why, one step back69store the string as Unicode by decoding the string with the characterRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 70–73why, one step back70encoding from the current Python module. If no encoding is specified this71defaults to 'ASCII' which means that you can't use any non ASCII identifier.7273To set a better module encoding add the following comment to the first orSome tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 74why, one step back74second line of the Python module using the Unicode literal::Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 75–82why, one step back7576 # -*- coding: utf-8 -*-7778We recommend utf-8 as Encoding for Python modules and templates as it's79possible to represent every Unicode character in utf-8 and because it's80backwards compatible to ASCII. For Jinja2 the default encoding of templates81is assumed to be utf-8.82Some tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 83why, one step back83It is not possible to use Jinja2 to process non-Unicode data. The reasonRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 84–86why, one step back84for this is that Jinja2 uses Unicode already on the language level. For85example Jinja2 treats the non-breaking space as valid whitespace inside86expressions which requires knowledge of the encoding or operating on anSome tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 87why, one step back87Unicode string.Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 88why, one step back88Some tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 89why, one step back89For more details about Unicode in Python have a look at the excellentRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 90–92why, one step back90`Unicode documentation`_.9192Another important thing is how Jinja2 is handling string literals inSome tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 93why, one step back93templates. A naive implementation would be using Unicode strings forRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 94–95why, one step back94all string literals but it turned out in the past that this is problematic95as some libraries are typechecking against `str` explicitly. For exampleSome tiny documentation fixes (unicode -> Unicode)Armin Ronacherbefore adoption656d5e7
line 96why, one step back96`datetime.strftime` does not accept Unicode arguments. To not break itRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 97–117why, one step back97completely Jinja2 is returning `str` for strings that fit into ASCII and98for everything else `unicode`:99100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module101>>> m.a102'foo'103>>> m.b104u'f\xf6\xf6'105106107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html108109High Level API110--------------111112The high-level API is the API you will use in the application to load and113render Jinja2 templates. The :ref:`low-level-api` on the other side is only114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115<jinja-extensions>`.116117.. autoclass:: Environment([options])include tags are now able to select between multiple templatesArmin Ronacherbefore adoption31bbd9e
lines 118–119why, one step back118 :members: from_string, get_template, select_template,119 get_or_select_template, join_path, extend, compile_expressionRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 120–164why, one step back120121 .. attribute:: shared122123 If a template was created by using the :class:`Template` constructor124 an environment is created automatically. These environments are125 created as shared environments which means that multiple templates126 may have the same anonymous environment. For all shared environments127 this attribute is `True`, else `False`.128129 .. attribute:: sandboxed130131 If the environment is sandboxed this attribute is `True`. For the132 sandbox mode have a look at the documentation for the133 :class:`~jinja2.sandbox.SandboxedEnvironment`.134135 .. attribute:: filters136137 A dict of filters for this environment. As long as no template was138 loaded it's safe to add new filters or remove old. For custom filters139 see :ref:`writing-filters`. For valid filter names have a look at140 :ref:`identifier-naming`.141142 .. attribute:: tests143144 A dict of test functions for this environment. As long as no145 template was loaded it's safe to modify this dict. For custom tests146 see :ref:`writing-tests`. For valid test names have a look at147 :ref:`identifier-naming`.148149 .. attribute:: globals150151 A dict of global variables. These variables are always available152 in a template. As long as no template was loaded it's safe153 to modify this dict. For more details see :ref:`global-namespace`.154 For valid object names have a look at :ref:`identifier-naming`.155156 .. automethod:: overlay([options])157158 .. method:: undefined([hint, obj, name, exc])159160 Creates a new :class:`Undefined` object for `name`. This is useful161 for filters or functions that may return undefined objects for162 some operations. All parameters except of `hint` should be provided163 as keyword parameters for better readability. The `hint` is used as164 error message for the exception if provided, otherwise the errorApplied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58
line 165why, one step back165 message will be generated from `obj` and `name` automatically. The exceptionRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 166–222why, one step back166 provided as `exc` is raised if something with the generated undefined167 object is done that the undefined object does not allow. The default168 exception is :exc:`UndefinedError`. If a `hint` is provided the169 `name` may be ommited.170171 The most common way to create an undefined object is by providing172 a name only::173174 return environment.undefined(name='some_name')175176 This means that the name `some_name` is not defined. If the name177 was from an attribute of an object it makes sense to tell the178 undefined object the holder object to improve the error message::179180 if not hasattr(obj, 'attr'):181 return environment.undefined(obj=obj, name='attr')182183 For a more complex example you can provide a hint. For example184 the :func:`first` filter creates an undefined object that way::185186 return environment.undefined('no first item, sequence was empty') 187188 If it the `name` or `obj` is known (for example because an attribute189 was accessed) it shold be passed to the undefined object, even if190 a custom `hint` is provided. This gives undefined objects the191 possibility to enhance the error message.192193.. autoclass:: Template194 :members: module, make_module195196 .. attribute:: globals197198 The dict with the globals of that template. It's unsafe to modify199 this dict as it may be shared with other templates or the environment200 that loaded the template.201202 .. attribute:: name203204 The loading name of the template. If the template was loaded from a205 string this is `None`.206207 .. attribute:: filename208209 The filename of the template on the file system if it was loaded from210 there. Otherwise this is `None`.211212 .. automethod:: render([context])213214 .. automethod:: generate([context])215216 .. automethod:: stream([context])217218219.. autoclass:: jinja2.environment.TemplateStream()220 :members: disable_buffering, enable_buffering, dump221222autoescape no longer is a plain boolean value but can also be a functionArmin Ronacherbefore adoption1da23d1
lines 223–254why, one step back223Autoescaping224------------225226.. versionadded:: 2.4227228As of Jinja 2.4 the preferred way to do autoescaping is to enable the229:ref:`autoescape-extension` and to configure a sensible default for230autoescaping. This makes it possible to enable and disable autoescaping231on a per-template basis (HTML versus text for instance).232233Here a recommended setup that enables autoescaping for templates ending234in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default235for all other extensions::236237 def guess_autoescape(template_name):238 if template_name is None or '.' not in template_name:239 return False240 ext = template_name.rsplit('.', 1)[1]241 return ext in ('html', 'htm', 'xml')242243 env = Environment(autoescape=guess_autoescape,244 loader=PackageLoader('mypackage'),245 extensions=['jinja2.ext.autoescape'])246247When implementing a guessing autoescape function, make sure you also248accept `None` as valid template name. This will be passed when generating249templates from strings.250251Inside the templates the behaviour can be temporarily changed by using252the `autoescape` block (see :ref:`autoescape-overrides`).253254Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 255–285why, one step back255.. _identifier-naming:256257Notes on Identifiers258--------------------259260Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to261match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters262are currently not allowed. This limitation will probably go away as soon as263unicode identifiers are fully specified for Python 3.264265Filters and tests are looked up in separate namespaces and have slightly266modified identifier syntax. Filters and tests may contain dots to group267filters and tests by topic. For example it's perfectly valid to add a268function into the filter dict and call it `to.unicode`. The regular269expression for filter and test identifiers is270``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.271272273Undefined Types274---------------275276These classes can be used as undefined types. The :class:`Environment`277constructor takes an `undefined` parameter that can be one of those classes278or a custom subclass of :class:`Undefined`. Whenever the template engine is279unable to look up a name or access an attribute one of those objects is280created and returned. Some operations on undefined values are then allowed,281others fail.282283The closest to regular Python behavior is the `StrictUndefined` which284disallows all operations beside testing if it's an undefined object.285Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 286why, one step back286.. autoclass:: jinja2.Undefined()Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 287–313why, one step back287288 .. attribute:: _undefined_hint289290 Either `None` or an unicode string with the error message for291 the undefined object.292293 .. attribute:: _undefined_obj294295 Either `None` or the owner object that caused the undefined object296 to be created (for example because an attribute does not exist).297298 .. attribute:: _undefined_name299300 The name for the undefined variable / attribute or just `None`301 if no such information exists.302303 .. attribute:: _undefined_exception304305 The exception that the undefined object wants to raise. This306 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.307308 .. method:: _fail_with_undefined_error(\*args, \**kwargs)309310 When called with any arguments this method raises311 :attr:`_undefined_exception` with an error message generated312 from the undefined hints stored on the undefined object.313Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 314why, one step back314.. autoclass:: jinja2.DebugUndefined()Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 315why, one step back315Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 316why, one step back316.. autoclass:: jinja2.StrictUndefined()Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 317–387why, one step back317318Undefined objects are created by calling :attr:`undefined`.319320.. admonition:: Implementation321322 :class:`Undefined` objects are implemented by overriding the special323 `__underscore__` methods. For example the default :class:`Undefined`324 class implements `__unicode__` in a way that it returns an empty325 string, however `__int__` and others still fail with an exception. To326 allow conversion to int by returning ``0`` you can implement your own::327328 class NullUndefined(Undefined):329 def __int__(self):330 return 0331 def __float__(self):332 return 0.0333334 To disallow a method, just override it and raise335 :attr:`~Undefined._undefined_exception`. Because this is a very common336 idom in undefined objects there is the helper method337 :meth:`~Undefined._fail_with_undefined_error` that does the error raising338 automatically. Here a class that works like the regular :class:`Undefined`339 but chokes on iteration::340341 class NonIterableUndefined(Undefined):342 __iter__ = Undefined._fail_with_undefined_error343344345The Context346-----------347348.. autoclass:: jinja2.runtime.Context()349 :members: resolve, get_exported, get_all350351 .. attribute:: parent352353 A dict of read only, global variables the template looks up. These354 can either come from another :class:`Context`, from the355 :attr:`Environment.globals` or :attr:`Template.globals` or points356 to a dict created by combining the globals with the variables357 passed to the render function. It must not be altered.358359 .. attribute:: vars360361 The template local variables. This list contains environment and362 context functions from the :attr:`parent` scope as well as local363 modifications and exported variables from the template. The template364 will modify this dict during template evaluation but filters and365 context functions are not allowed to modify it.366367 .. attribute:: environment368369 The environment that loaded the template.370371 .. attribute:: exported_vars372373 This set contains all the names the template exports. The values for374 the names are in the :attr:`vars` dict. In order to get a copy of the375 exported variables as dict, :meth:`get_exported` can be used.376377 .. attribute:: name378379 The load name of the template owning this context.380381 .. attribute:: blocks382383 A dict with the current mapping of blocks in the template. The keys384 in this dict are the names of the blocks, and the values a list of385 blocks registered. The last item in each list is the current active386 block (latest in the inheritance chain).387Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 388–391why, one step back388 .. attribute:: eval_ctx389390 The current :ref:`eval-context`.391Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 392–418why, one step back392 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)393394395.. admonition:: Implementation396397 Context is immutable for the same reason Python's frame locals are398 immutable inside functions. Both Jinja2 and Python are not using the399 context / frame locals as data storage for variables but only as primary400 data source.401402 When a template accesses a variable the template does not define, Jinja2403 looks up the variable in the context, after that the variable is treated404 as if it was defined in the template.405406407.. _loaders:408409Loaders410-------411412Loaders are responsible for loading templates from a resource such as the413file system. The environment will keep the compiled modules in memory like414Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in415size by default and templates are automatically reloaded.416All loaders are subclasses of :class:`BaseLoader`. If you want to create your417own loader, subclass :class:`BaseLoader` and override `get_source`.418Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 419why, one step back419.. autoclass:: jinja2.BaseLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 420–423why, one step back420 :members: get_source, load421422Here a list of the builtin loaders Jinja2 provides:423Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 424why, one step back424.. autoclass:: jinja2.FileSystemLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 425why, one step back425Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 426why, one step back426.. autoclass:: jinja2.PackageLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 427why, one step back427Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 428why, one step back428.. autoclass:: jinja2.DictLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 429why, one step back429Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 430why, one step back430.. autoclass:: jinja2.FunctionLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 431why, one step back431Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 432why, one step back432.. autoclass:: jinja2.PrefixLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 433why, one step back433Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 434why, one step back434.. autoclass:: jinja2.ChoiceLoaderRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 435–436why, one step back435436Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
lines 437–475why, one step back437.. _bytecode-cache:438439Bytecode Cache440--------------441442Jinja 2.1 and higher support external bytecode caching. Bytecode caches make443it possible to store the generated bytecode on the file system or a different444location to avoid parsing the templates on first use.445446This is especially useful if you have a web application that is initialized on447the first request and Jinja compiles many templates at once which slows down448the application.449450To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.451452.. autoclass:: jinja2.BytecodeCache453 :members: load_bytecode, dump_bytecode, clear454455.. autoclass:: jinja2.bccache.Bucket456 :members: write_bytecode, load_bytecode, bytecode_from_string,457 bytecode_to_string, reset458459 .. attribute:: environment460461 The :class:`Environment` that created the bucket.462463 .. attribute:: key464465 The unique cache key for this bucket466467 .. attribute:: code468469 The bytecode if it's loaded, otherwise `None`.470471472Builtin bytecode caches:473474.. autoclass:: jinja2.FileSystemBytecodeCache475Fixed bytecode cache and added support for memcached (tests still missing)Armin Ronacherbefore adoptionaa1d17d
lines 476–477why, one step back476.. autoclass:: jinja2.MemcachedBytecodeCache477Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 478why, one step back478Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 479–484why, one step back479Utilities480---------481482These helper functions and classes are useful if you add custom filters or483functions to a Jinja2 environment.484Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 485why, one step back485.. autofunction:: jinja2.environmentfilterRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 486why, one step back486Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 487why, one step back487.. autofunction:: jinja2.contextfilterRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 488why, one step back488Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 489–490why, one step back489.. autofunction:: jinja2.evalcontextfilter490Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 491why, one step back491.. autofunction:: jinja2.environmentfunctionRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 492why, one step back492Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 493why, one step back493.. autofunction:: jinja2.contextfunctionRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 494why, one step back494Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 495–496why, one step back495.. autofunction:: jinja2.evalcontextfunction496Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 497–505why, one step back497.. function:: escape(s)498499 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`500 to HTML-safe sequences. Use this if you need to display text that might501 contain such characters in HTML. This function will not escaped objects502 that do have an HTML representation such as already escaped data.503504 The return value is a :class:`Markup` string.505Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 506why, one step back506.. autofunction:: jinja2.clear_cachesRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 507why, one step back507Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 508why, one step back508.. autofunction:: jinja2.is_undefinedRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 509why, one step back509Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 510why, one step back510.. autoclass:: jinja2.Markup([string])Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 511–522why, one step back511 :members: escape, unescape, striptags512513.. admonition:: Note514515 The Jinja2 :class:`Markup` class is compatible with at least Pylons and516 Genshi. It's expected that more template engines and framework will pick517 up the `__html__` concept soon.518519520Exceptions521----------522Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 523why, one step back523.. autoexception:: jinja2.TemplateErrorRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 524why, one step back524Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 525why, one step back525.. autoexception:: jinja2.UndefinedErrorRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 526why, one step back526Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 527why, one step back527.. autoexception:: jinja2.TemplateNotFoundinclude tags are now able to select between multiple templatesArmin Ronacherbefore adoption31bbd9e
lines 528–529why, one step back528529.. autoexception:: jinja2.TemplatesNotFoundRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 530why, one step back530Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 531why, one step back531.. autoexception:: jinja2.TemplateSyntaxErrorRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 532–553why, one step back532533 .. attribute:: message534535 The error message as utf-8 bytestring.536537 .. attribute:: lineno538539 The line number where the error occurred540541 .. attribute:: name542543 The load name for the template as unicode string.544545 .. attribute:: filename546547 The filename that loaded the template as bytestring in the encoding548 of the file system (most likely utf-8 or mbcs on Windows systems).549550 The reason why the filename and error message are bytestrings and not551 unicode strings is that Python 2.x is not using unicode for exceptions552 and tracebacks as well as the compiler. This will change with Python 3.553Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4
line 554why, one step back554.. autoexception:: jinja2.TemplateAssertionErrorRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 555–585why, one step back555556557.. _writing-filters:558559Custom Filters560--------------561562Custom filters are just regular Python functions that take the left side of563the filter as first argument and the the arguments passed to the filter as564extra arguments or keyword arguments.565566For example in the filter ``{{ 42|myfilter(23) }}`` the function would be567called with ``myfilter(42, 23)``. Here for example a simple filter that can568be applied to datetime objects to format them::569570 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):571 return value.strftime(format)572573You can register it on the template environment by updating the574:attr:`~Environment.filters` dict on the environment::575576 environment.filters['datetimeformat'] = datetimeformat577578Inside the template it can then be used as follows:579580.. sourcecode:: jinja581582 written on: {{ article.pub_date|datetimeformat }}583 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}584585Filters can also be passed the current template context or environment. ThisApplied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58
line 586why, one step back586is useful if a filter wants to return an undefined value or check the currentthree is the new twoArmin Ronacherbefore adoption2e3c9c7
line 587why, one step back587:attr:`~Environment.autoescape` setting. For this purpose three decoratorsDocumented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 588–589why, one step back588exist: :func:`environmentfilter`, :func:`contextfilter` and589:func:`evalcontextfilter`.Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 590–599why, one step back590591Here a small example filter that breaks a text into HTML line breaks and592paragraphs and marks the return value as safe HTML string if autoescaping is593enabled::594595 import re596 from jinja2 import environmentfilter, Markup, escape597598 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')599Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 600–601why, one step back600 @evalcontextfilter601 def nl2br(eval_ctx, value):Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 602–603why, one step back602 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')603 for p in _paragraph_re.split(escape(value)))Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
line 604why, one step back604 if eval_ctx.autoescape:Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 605–610why, one step back605 result = Markup(result)606 return result607608Context filters work the same just that the first argument is the current609active :class:`Context` rather then the environment.610Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3
lines 611–660why, one step back611612.. _eval-context:613614Evaluation Context615------------------616617The evaluation context (short eval context or eval ctx) is a new object618introducted in Jinja 2.4 that makes it possible to activate and deactivate619compiled features at runtime.620621Currently it is only used to enable and disable the automatic escaping but622can be used for extensions as well.623624In previous Jinja versions filters and functions were marked as625environment callables in order to check for the autoescape status from the626environment. In new versions it's encouraged to check the setting from the627evaluation context instead.628629Previous versions::630631 @environmentfilter632 def filter(env, value):633 result = do_something(value)634 if env.autoescape:635 result = Markup(result)636 return result637638In new versions you can either use a :func:`contextfilter` and access the639evaluation context from the actual context, or use a640:func:`evalcontextfilter` which directly passes the evaluation context to641the function::642643 @contextfilter644 def filter(context, value):645 result = do_something(value)646 if context.eval_ctx.autoescape:647 result = Markup(result)648 return result649650 @evalcontextfilter651 def filter(eval_ctx, value):652 result = do_something(value)653 if eval_ctx.autoescape:654 result = Markup(result)655 return result656657The evaluation context must not be modified at runtime. Modifications658must only happen with a :class:`nodes.EvalContextModifier` and659:class:`nodes.ScopedEvalContextModifier` from an extension, not on the660eval context object itself.Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 661why, one step back661Hopefully fixed EvalContext documentation.Armin Ronacherbefore adoption76ae15e
line 662why, one step back662.. autoclass:: jinja2.nodes.EvalContextMore documentation updates.Armin Ronacherbefore adoption30fda27
lines 663–673why, one step back663664 .. attribute:: autoescape665666 `True` or `False` depending on if autoescaping is active or not.667668 .. attribute:: volatile669670 `True` if the compiler cannot evaluate some expressions at compile671 time. At runtime this should always be `False`.672673Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 674–678why, one step back674.. _writing-tests:675676Custom Tests677------------678filter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55
line 679why, one step back679Tests work like filters just that there is no way for a test to get accessRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 680why, one step back680to the environment or context and that they can't be chained. The returnfilter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55
line 681why, one step back681value of a test should be `True` or `False`. The purpose of a test is toRemoved a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 682–684why, one step back682give the template designers the possibility to perform type and conformability683checks.684filter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55
line 685why, one step back685Here a simple test that checks if a variable is a prime number::Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
lines 686–773why, one step back686687 import math688689 def is_prime(n):690 if n == 2:691 return True692 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):693 if n % i == 0:694 return False695 return True696 697698You can register it on the template environment by updating the699:attr:`~Environment.tests` dict on the environment::700701 environment.tests['prime'] = is_prime702703A template designer can then use the test like this:704705.. sourcecode:: jinja706707 {% if 42 is prime %}708 42 is a prime number709 {% else %}710 42 is not a prime number711 {% endif %}712713714.. _global-namespace:715716The Global Namespace717--------------------718719Variables stored in the :attr:`Environment.globals` dict are special as they720are available for imported templates too, even if they are imported without721context. This is the place where you can put variables and functions722that should be available all the time. Additionally :attr:`Template.globals`723exist that are variables available to a specific template that are available724to all :meth:`~Template.render` calls.725726727.. _low-level-api:728729Low Level API730-------------731732The low level API exposes functionality that can be useful to understand some733implementation details, debugging purposes or advanced :ref:`extension734<jinja-extensions>` techniques. Unless you know exactly what you are doing we735don't recommend using any of those.736737.. automethod:: Environment.lex738739.. automethod:: Environment.parse740741.. automethod:: Environment.preprocess742743.. automethod:: Template.new_context744745.. method:: Template.root_render_func(context)746747 This is the low level render function. It's passed a :class:`Context`748 that has to be created by :meth:`new_context` of the same template or749 a compatible template. This render function is generated by the750 compiler from the template code and returns a generator that yields751 unicode strings.752753 If an exception in the template code happens the template engine will754 not rewrite the exception but pass through the original one. As a755 matter of fact this function should only be called from within a756 :meth:`render` / :meth:`generate` / :meth:`stream` call.757758.. attribute:: Template.blocks759760 A dict of block render functions. Each of these functions works exactly761 like the :meth:`root_render_func` with the same limitations.762763.. attribute:: Template.is_up_to_date764765 This attribute is `False` if there is a newer version of the template766 available, otherwise `True`.767768.. admonition:: Note769770 The low-level API is fragile. Future Jinja2 versions will try not to771 change it in a backwards incompatible way but modifications in the Jinja2772 core may shine through. For example if Jinja2 introduces a new AST node773 in later versions that may be returned by :meth:`~Environment.parse`.Added the `meta` module.Armin Ronacherbefore adoption63cf9b8
lines 774–787why, one step back774775The Meta API776------------777778.. versionadded:: 2.2779780The meta API returns some information about abstract syntax trees that781could help applications to implement more advanced template concepts. All782the functions of the meta API operate on an abstract syntax tree as783returned by the :meth:`Environment.parse` method.784785.. autofunction:: jinja2.meta.find_undeclared_variables786787.. autofunction:: jinja2.meta.find_referenced_templates