api.rst
This file
Path
docs/api.rst
795 lines · 27.1 KiB
Last changed by
Added tests for logging undefined and added it to the docs.Armin Ronacherbefore adoption6e9dfbf
History of this fileTake it
The walk stopped after 200 commits: lines older than d90f050 point at it.
Fixed filesizeformat filter. It should now conform to the official SI prefixes and use the correct prefixes for sizes greater than base ** 4.Alan Plumbefore adoptiond90f050
lines 1–119why, 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.17Even if you are creating templates from strings by using the constructor of18: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-------5455Jinja2 is using Unicode internally which means that you have to pass Unicode56objects 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 are64used. With Python 2.6 it is possible to make `unicode` the default on a per65module level and with Python 3 it will be the default.6667To explicitly use a Unicode string you have to prefix the string literal68with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will69store the string as Unicode by decoding the string with the character70encoding 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 or74second line of the Python module using the Unicode literal::7576 # -*- 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.8283It is not possible to use Jinja2 to process non-Unicode data. The reason84for 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 an87Unicode string.8889For more details about Unicode in Python have a look at the excellent90`Unicode documentation`_.9192Another important thing is how Jinja2 is handling string literals in93templates. A naive implementation would be using Unicode strings for94all string literals but it turned out in the past that this is problematic95as some libraries are typechecking against `str` explicitly. For example96`datetime.strftime` does not accept Unicode arguments. To not break it97completely 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])118 :members: from_string, get_template, select_template,119 get_or_select_template, join_path, extend, compile_expression,Added add_extension method to the public APIArmin Ronacherbefore adoption9463850
line 120why, one step back120 compile_templates, list_templates, add_extensionFixed filesizeformat filter. It should now conform to the official SI prefixes and use the correct prefixes for sizes greater than base ** 4.Alan Plumbefore adoptiond90f050
lines 121–318why, one step back121122 .. attribute:: shared123124 If a template was created by using the :class:`Template` constructor125 an environment is created automatically. These environments are126 created as shared environments which means that multiple templates127 may have the same anonymous environment. For all shared environments128 this attribute is `True`, else `False`.129130 .. attribute:: sandboxed131132 If the environment is sandboxed this attribute is `True`. For the133 sandbox mode have a look at the documentation for the134 :class:`~jinja2.sandbox.SandboxedEnvironment`.135136 .. attribute:: filters137138 A dict of filters for this environment. As long as no template was139 loaded it's safe to add new filters or remove old. For custom filters140 see :ref:`writing-filters`. For valid filter names have a look at141 :ref:`identifier-naming`.142143 .. attribute:: tests144145 A dict of test functions for this environment. As long as no146 template was loaded it's safe to modify this dict. For custom tests147 see :ref:`writing-tests`. For valid test names have a look at148 :ref:`identifier-naming`.149150 .. attribute:: globals151152 A dict of global variables. These variables are always available153 in a template. As long as no template was loaded it's safe154 to modify this dict. For more details see :ref:`global-namespace`.155 For valid object names have a look at :ref:`identifier-naming`.156157 .. automethod:: overlay([options])158159 .. method:: undefined([hint, obj, name, exc])160161 Creates a new :class:`Undefined` object for `name`. This is useful162 for filters or functions that may return undefined objects for163 some operations. All parameters except of `hint` should be provided164 as keyword parameters for better readability. The `hint` is used as165 error message for the exception if provided, otherwise the error166 message will be generated from `obj` and `name` automatically. The exception167 provided as `exc` is raised if something with the generated undefined168 object is done that the undefined object does not allow. The default169 exception is :exc:`UndefinedError`. If a `hint` is provided the170 `name` may be ommited.171172 The most common way to create an undefined object is by providing173 a name only::174175 return environment.undefined(name='some_name')176177 This means that the name `some_name` is not defined. If the name178 was from an attribute of an object it makes sense to tell the179 undefined object the holder object to improve the error message::180181 if not hasattr(obj, 'attr'):182 return environment.undefined(obj=obj, name='attr')183184 For a more complex example you can provide a hint. For example185 the :func:`first` filter creates an undefined object that way::186187 return environment.undefined('no first item, sequence was empty') 188189 If it the `name` or `obj` is known (for example because an attribute190 was accessed) it shold be passed to the undefined object, even if191 a custom `hint` is provided. This gives undefined objects the192 possibility to enhance the error message.193194.. autoclass:: Template195 :members: module, make_module196197 .. attribute:: globals198199 The dict with the globals of that template. It's unsafe to modify200 this dict as it may be shared with other templates or the environment201 that loaded the template.202203 .. attribute:: name204205 The loading name of the template. If the template was loaded from a206 string this is `None`.207208 .. attribute:: filename209210 The filename of the template on the file system if it was loaded from211 there. Otherwise this is `None`.212213 .. automethod:: render([context])214215 .. automethod:: generate([context])216217 .. automethod:: stream([context])218219220.. autoclass:: jinja2.environment.TemplateStream()221 :members: disable_buffering, enable_buffering, dump222223224Autoescaping225------------226227.. versionadded:: 2.4228229As of Jinja 2.4 the preferred way to do autoescaping is to enable the230:ref:`autoescape-extension` and to configure a sensible default for231autoescaping. This makes it possible to enable and disable autoescaping232on a per-template basis (HTML versus text for instance).233234Here a recommended setup that enables autoescaping for templates ending235in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default236for all other extensions::237238 def guess_autoescape(template_name):239 if template_name is None or '.' not in template_name:240 return False241 ext = template_name.rsplit('.', 1)[1]242 return ext in ('html', 'htm', 'xml')243244 env = Environment(autoescape=guess_autoescape,245 loader=PackageLoader('mypackage'),246 extensions=['jinja2.ext.autoescape'])247248When implementing a guessing autoescape function, make sure you also249accept `None` as valid template name. This will be passed when generating250templates from strings.251252Inside the templates the behaviour can be temporarily changed by using253the `autoescape` block (see :ref:`autoescape-overrides`).254255256.. _identifier-naming:257258Notes on Identifiers259--------------------260261Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to262match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters263are currently not allowed. This limitation will probably go away as soon as264unicode identifiers are fully specified for Python 3.265266Filters and tests are looked up in separate namespaces and have slightly267modified identifier syntax. Filters and tests may contain dots to group268filters and tests by topic. For example it's perfectly valid to add a269function into the filter dict and call it `to.unicode`. The regular270expression for filter and test identifiers is271``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.272273274Undefined Types275---------------276277These classes can be used as undefined types. The :class:`Environment`278constructor takes an `undefined` parameter that can be one of those classes279or a custom subclass of :class:`Undefined`. Whenever the template engine is280unable to look up a name or access an attribute one of those objects is281created and returned. Some operations on undefined values are then allowed,282others fail.283284The closest to regular Python behavior is the `StrictUndefined` which285disallows all operations beside testing if it's an undefined object.286287.. autoclass:: jinja2.Undefined()288289 .. attribute:: _undefined_hint290291 Either `None` or an unicode string with the error message for292 the undefined object.293294 .. attribute:: _undefined_obj295296 Either `None` or the owner object that caused the undefined object297 to be created (for example because an attribute does not exist).298299 .. attribute:: _undefined_name300301 The name for the undefined variable / attribute or just `None`302 if no such information exists.303304 .. attribute:: _undefined_exception305306 The exception that the undefined object wants to raise. This307 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.308309 .. method:: _fail_with_undefined_error(\*args, \**kwargs)310311 When called with any arguments this method raises312 :attr:`_undefined_exception` with an error message generated313 from the undefined hints stored on the undefined object.314315.. autoclass:: jinja2.DebugUndefined()316317.. autoclass:: jinja2.StrictUndefined()318Added tests for logging undefined and added it to the docs.Armin Ronacherbefore adoption6e9dfbf
lines 319–323why, one step back319There is also a factory function that can decorate undefined objects to320implement logging on failures:321322.. autofunction:: jinja2.make_logging_undefined323Fixed filesizeformat filter. It should now conform to the official SI prefixes and use the correct prefixes for sizes greater than base ** 4.Alan Plumbefore adoptiond90f050
lines 324–603why, one step back324Undefined objects are created by calling :attr:`undefined`.325326.. admonition:: Implementation327328 :class:`Undefined` objects are implemented by overriding the special329 `__underscore__` methods. For example the default :class:`Undefined`330 class implements `__unicode__` in a way that it returns an empty331 string, however `__int__` and others still fail with an exception. To332 allow conversion to int by returning ``0`` you can implement your own::333334 class NullUndefined(Undefined):335 def __int__(self):336 return 0337 def __float__(self):338 return 0.0339340 To disallow a method, just override it and raise341 :attr:`~Undefined._undefined_exception`. Because this is a very common342 idom in undefined objects there is the helper method343 :meth:`~Undefined._fail_with_undefined_error` that does the error raising344 automatically. Here a class that works like the regular :class:`Undefined`345 but chokes on iteration::346347 class NonIterableUndefined(Undefined):348 __iter__ = Undefined._fail_with_undefined_error349350351The Context352-----------353354.. autoclass:: jinja2.runtime.Context()355 :members: resolve, get_exported, get_all356357 .. attribute:: parent358359 A dict of read only, global variables the template looks up. These360 can either come from another :class:`Context`, from the361 :attr:`Environment.globals` or :attr:`Template.globals` or points362 to a dict created by combining the globals with the variables363 passed to the render function. It must not be altered.364365 .. attribute:: vars366367 The template local variables. This list contains environment and368 context functions from the :attr:`parent` scope as well as local369 modifications and exported variables from the template. The template370 will modify this dict during template evaluation but filters and371 context functions are not allowed to modify it.372373 .. attribute:: environment374375 The environment that loaded the template.376377 .. attribute:: exported_vars378379 This set contains all the names the template exports. The values for380 the names are in the :attr:`vars` dict. In order to get a copy of the381 exported variables as dict, :meth:`get_exported` can be used.382383 .. attribute:: name384385 The load name of the template owning this context.386387 .. attribute:: blocks388389 A dict with the current mapping of blocks in the template. The keys390 in this dict are the names of the blocks, and the values a list of391 blocks registered. The last item in each list is the current active392 block (latest in the inheritance chain).393394 .. attribute:: eval_ctx395396 The current :ref:`eval-context`.397398 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)399400401.. admonition:: Implementation402403 Context is immutable for the same reason Python's frame locals are404 immutable inside functions. Both Jinja2 and Python are not using the405 context / frame locals as data storage for variables but only as primary406 data source.407408 When a template accesses a variable the template does not define, Jinja2409 looks up the variable in the context, after that the variable is treated410 as if it was defined in the template.411412413.. _loaders:414415Loaders416-------417418Loaders are responsible for loading templates from a resource such as the419file system. The environment will keep the compiled modules in memory like420Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in421size by default and templates are automatically reloaded.422All loaders are subclasses of :class:`BaseLoader`. If you want to create your423own loader, subclass :class:`BaseLoader` and override `get_source`.424425.. autoclass:: jinja2.BaseLoader426 :members: get_source, load427428Here a list of the builtin loaders Jinja2 provides:429430.. autoclass:: jinja2.FileSystemLoader431432.. autoclass:: jinja2.PackageLoader433434.. autoclass:: jinja2.DictLoader435436.. autoclass:: jinja2.FunctionLoader437438.. autoclass:: jinja2.PrefixLoader439440.. autoclass:: jinja2.ChoiceLoader441442.. autoclass:: jinja2.ModuleLoader443444445.. _bytecode-cache:446447Bytecode Cache448--------------449450Jinja 2.1 and higher support external bytecode caching. Bytecode caches make451it possible to store the generated bytecode on the file system or a different452location to avoid parsing the templates on first use.453454This is especially useful if you have a web application that is initialized on455the first request and Jinja compiles many templates at once which slows down456the application.457458To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.459460.. autoclass:: jinja2.BytecodeCache461 :members: load_bytecode, dump_bytecode, clear462463.. autoclass:: jinja2.bccache.Bucket464 :members: write_bytecode, load_bytecode, bytecode_from_string,465 bytecode_to_string, reset466467 .. attribute:: environment468469 The :class:`Environment` that created the bucket.470471 .. attribute:: key472473 The unique cache key for this bucket474475 .. attribute:: code476477 The bytecode if it's loaded, otherwise `None`.478479480Builtin bytecode caches:481482.. autoclass:: jinja2.FileSystemBytecodeCache483484.. autoclass:: jinja2.MemcachedBytecodeCache485486487Utilities488---------489490These helper functions and classes are useful if you add custom filters or491functions to a Jinja2 environment.492493.. autofunction:: jinja2.environmentfilter494495.. autofunction:: jinja2.contextfilter496497.. autofunction:: jinja2.evalcontextfilter498499.. autofunction:: jinja2.environmentfunction500501.. autofunction:: jinja2.contextfunction502503.. autofunction:: jinja2.evalcontextfunction504505.. function:: escape(s)506507 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`508 to HTML-safe sequences. Use this if you need to display text that might509 contain such characters in HTML. This function will not escaped objects510 that do have an HTML representation such as already escaped data.511512 The return value is a :class:`Markup` string.513514.. autofunction:: jinja2.clear_caches515516.. autofunction:: jinja2.is_undefined517518.. autoclass:: jinja2.Markup([string])519 :members: escape, unescape, striptags520521.. admonition:: Note522523 The Jinja2 :class:`Markup` class is compatible with at least Pylons and524 Genshi. It's expected that more template engines and framework will pick525 up the `__html__` concept soon.526527528Exceptions529----------530531.. autoexception:: jinja2.TemplateError532533.. autoexception:: jinja2.UndefinedError534535.. autoexception:: jinja2.TemplateNotFound536537.. autoexception:: jinja2.TemplatesNotFound538539.. autoexception:: jinja2.TemplateSyntaxError540541 .. attribute:: message542543 The error message as utf-8 bytestring.544545 .. attribute:: lineno546547 The line number where the error occurred548549 .. attribute:: name550551 The load name for the template as unicode string.552553 .. attribute:: filename554555 The filename that loaded the template as bytestring in the encoding556 of the file system (most likely utf-8 or mbcs on Windows systems).557558 The reason why the filename and error message are bytestrings and not559 unicode strings is that Python 2.x is not using unicode for exceptions560 and tracebacks as well as the compiler. This will change with Python 3.561562.. autoexception:: jinja2.TemplateAssertionError563564565.. _writing-filters:566567Custom Filters568--------------569570Custom filters are just regular Python functions that take the left side of571the filter as first argument and the the arguments passed to the filter as572extra arguments or keyword arguments.573574For example in the filter ``{{ 42|myfilter(23) }}`` the function would be575called with ``myfilter(42, 23)``. Here for example a simple filter that can576be applied to datetime objects to format them::577578 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):579 return value.strftime(format)580581You can register it on the template environment by updating the582:attr:`~Environment.filters` dict on the environment::583584 environment.filters['datetimeformat'] = datetimeformat585586Inside the template it can then be used as follows:587588.. sourcecode:: jinja589590 written on: {{ article.pub_date|datetimeformat }}591 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}592593Filters can also be passed the current template context or environment. This594is useful if a filter wants to return an undefined value or check the current595:attr:`~Environment.autoescape` setting. For this purpose three decorators596exist: :func:`environmentfilter`, :func:`contextfilter` and597:func:`evalcontextfilter`.598599Here a small example filter that breaks a text into HTML line breaks and600paragraphs and marks the return value as safe HTML string if autoescaping is601enabled::602603 import reMerge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption8a05e93
line 604why, one step back604 from jinja2 import evalcontextfilter, Markup, escapeFixed filesizeformat filter. It should now conform to the official SI prefixes and use the correct prefixes for sizes greater than base ** 4.Alan Plumbefore adoptiond90f050
lines 605–795why, one step back605606 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')607608 @evalcontextfilter609 def nl2br(eval_ctx, value):610 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')611 for p in _paragraph_re.split(escape(value)))612 if eval_ctx.autoescape:613 result = Markup(result)614 return result615616Context filters work the same just that the first argument is the current617active :class:`Context` rather then the environment.618619620.. _eval-context:621622Evaluation Context623------------------624625The evaluation context (short eval context or eval ctx) is a new object626introducted in Jinja 2.4 that makes it possible to activate and deactivate627compiled features at runtime.628629Currently it is only used to enable and disable the automatic escaping but630can be used for extensions as well.631632In previous Jinja versions filters and functions were marked as633environment callables in order to check for the autoescape status from the634environment. In new versions it's encouraged to check the setting from the635evaluation context instead.636637Previous versions::638639 @environmentfilter640 def filter(env, value):641 result = do_something(value)642 if env.autoescape:643 result = Markup(result)644 return result645646In new versions you can either use a :func:`contextfilter` and access the647evaluation context from the actual context, or use a648:func:`evalcontextfilter` which directly passes the evaluation context to649the function::650651 @contextfilter652 def filter(context, value):653 result = do_something(value)654 if context.eval_ctx.autoescape:655 result = Markup(result)656 return result657658 @evalcontextfilter659 def filter(eval_ctx, value):660 result = do_something(value)661 if eval_ctx.autoescape:662 result = Markup(result)663 return result664665The evaluation context must not be modified at runtime. Modifications666must only happen with a :class:`nodes.EvalContextModifier` and667:class:`nodes.ScopedEvalContextModifier` from an extension, not on the668eval context object itself.669670.. autoclass:: jinja2.nodes.EvalContext671672 .. attribute:: autoescape673674 `True` or `False` depending on if autoescaping is active or not.675676 .. attribute:: volatile677678 `True` if the compiler cannot evaluate some expressions at compile679 time. At runtime this should always be `False`.680681682.. _writing-tests:683684Custom Tests685------------686687Tests work like filters just that there is no way for a test to get access688to the environment or context and that they can't be chained. The return689value of a test should be `True` or `False`. The purpose of a test is to690give the template designers the possibility to perform type and conformability691checks.692693Here a simple test that checks if a variable is a prime number::694695 import math696697 def is_prime(n):698 if n == 2:699 return True700 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):701 if n % i == 0:702 return False703 return True704 705706You can register it on the template environment by updating the707:attr:`~Environment.tests` dict on the environment::708709 environment.tests['prime'] = is_prime710711A template designer can then use the test like this:712713.. sourcecode:: jinja714715 {% if 42 is prime %}716 42 is a prime number717 {% else %}718 42 is not a prime number719 {% endif %}720721722.. _global-namespace:723724The Global Namespace725--------------------726727Variables stored in the :attr:`Environment.globals` dict are special as they728are available for imported templates too, even if they are imported without729context. This is the place where you can put variables and functions730that should be available all the time. Additionally :attr:`Template.globals`731exist that are variables available to a specific template that are available732to all :meth:`~Template.render` calls.733734735.. _low-level-api:736737Low Level API738-------------739740The low level API exposes functionality that can be useful to understand some741implementation details, debugging purposes or advanced :ref:`extension742<jinja-extensions>` techniques. Unless you know exactly what you are doing we743don't recommend using any of those.744745.. automethod:: Environment.lex746747.. automethod:: Environment.parse748749.. automethod:: Environment.preprocess750751.. automethod:: Template.new_context752753.. method:: Template.root_render_func(context)754755 This is the low level render function. It's passed a :class:`Context`756 that has to be created by :meth:`new_context` of the same template or757 a compatible template. This render function is generated by the758 compiler from the template code and returns a generator that yields759 unicode strings.760761 If an exception in the template code happens the template engine will762 not rewrite the exception but pass through the original one. As a763 matter of fact this function should only be called from within a764 :meth:`render` / :meth:`generate` / :meth:`stream` call.765766.. attribute:: Template.blocks767768 A dict of block render functions. Each of these functions works exactly769 like the :meth:`root_render_func` with the same limitations.770771.. attribute:: Template.is_up_to_date772773 This attribute is `False` if there is a newer version of the template774 available, otherwise `True`.775776.. admonition:: Note777778 The low-level API is fragile. Future Jinja2 versions will try not to779 change it in a backwards incompatible way but modifications in the Jinja2780 core may shine through. For example if Jinja2 introduces a new AST node781 in later versions that may be returned by :meth:`~Environment.parse`.782783The Meta API784------------785786.. versionadded:: 2.2787788The meta API returns some information about abstract syntax trees that789could help applications to implement more advanced template concepts. All790the functions of the meta API operate on an abstract syntax tree as791returned by the :meth:`Environment.parse` method.792793.. autofunction:: jinja2.meta.find_undeclared_variables794795.. autofunction:: jinja2.meta.find_referenced_templates