?????????????? ?????????????? ?????????????? ?????????????? PKê|>]èÉÇx||$examples/basic/templates/broken.htmlnu„[µü¤{% from 'subbroken.html' import may_break %} PKê|>]”*D @@'examples/basic/templates/subbroken.htmlnu„[µü¤{% macro may_break(item) -%} [{{ item / 0 }}] {%- endmacro %} PKê|>];÷¸examples/basic/cycle.pynu„[µü¤from jinja2 import Environment env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}") print env.from_string("""\ \ """).render() PKê|>]›V ßßexamples/basic/debugger.pynu„[µü¤from jinja2 import Environment from jinja2.loaders import FileSystemLoader env = Environment(loader=FileSystemLoader('templates')) tmpl = env.get_template('broken.html') print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]) PKê|>]Çêâ‚UUexamples/basic/inheritance.pynu„[µü¤from jinja2 import Environment from jinja2.loaders import DictLoader env = Environment(loader=DictLoader({ 'a': '''[A[{% block body %}{% endblock %}]]''', 'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''', 'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}''' })) print env.get_template('c').render() PKê|>]ÚNñddexamples/basic/test.pynu„[µü¤from jinja2 import Environment from jinja2.loaders import DictLoader env = Environment(loader=DictLoader({ 'child.html': u'''\ {% extends master_layout or 'master.html' %} {% include helpers = 'helpers.html' %} {% macro get_the_answer() %}42{% endmacro %} {% title = 'Hello World' %} {% block body %} {{ get_the_answer() }} {{ helpers.conspirate() }} {% endblock %} ''', 'master.html': u'''\ {{ title }} {% block body %}{% endblock %} ''', 'helpers.html': u'''\ {% macro conspirate() %}23{% endmacro %} ''' })) tmpl = env.get_template("child.html") print(tmpl.render()) PKê|>]oåfN¾¾0examples/basic/test_filter_and_linestatements.pynu„[µü¤from jinja2 import Environment env = Environment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}") tmpl = env.from_string("""\ % macro foo() ${caller(42)} % endmacro % call(var) foo() [${var}] % endcall % filter escape % for item in [1, 2, 3] - ${item} % endfor % endfilter """) print(tmpl.render(seq=range(10))) PKê|>]½òÉ¿(("examples/basic/test_loop_filter.pynu„[µü¤from jinja2 import Environment tmpl = Environment().from_string("""\ if condition: {{ 1 if foo else 0 }} """) print(tmpl.render(foo=True)) PKê|>]�ÙÜ   examples/basic/translate.pynu„[µü¤from jinja2 import Environment env = Environment(extensions=['jinja2.ext.i18n']) env.globals['gettext'] = { 'Hello %(user)s!': 'Hallo %(user)s!' }.__getitem__ env.globals['ngettext'] = lambda s, p, n: { '%(count)s user': '%(count)d Benutzer', '%(count)s users': '%(count)d Benutzer' }[n == 1 and s or p] print env.from_string("""\ {% trans %}Hello {{ user }}!{% endtrans %} {% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %} """).render(user="someone", users=[1, 2, 3]) PKê|>]�¨†ŸDD"examples/rwbench/django/_form.htmlnu„[µü¤
{{ body }}
PKê|>]îÞ‡¼@@)examples/rwbench/django/_input_field.htmlnu„[µü¤ PKê|>]Ô€ãWW&examples/rwbench/django/_textarea.htmlnu„[µü¤ PKê|>]Ówn¨¨"examples/rwbench/django/index.htmlnu„[µü¤{% extends "layout.html" %} {% block page_title %}Index Page{% endblock %} {% block body %} {% for article in articles %} {% if article.published %}

{{ article.title }}

written by {{ article.user.username }} on {{ article.pub_date|dateformat }}

{{ article.body|safe }}
{% endif %} {% endfor %} {% form %}
Name
{% input_field 'name' %}
E-Mail
{% input_field 'email' %}
URL
{% input_field 'url' %}
Comment
{% textarea 'comment' %}
Captcha
{% input_field 'captcha' %}
{% input_field '' 'submit' 'Submit' %} {% input_field 'cancel' 'submit' 'Cancel' %} {% endform %} {% endblock %} PKê|>]=|†gg#examples/rwbench/django/layout.htmlnu„[µü¤ {% block page_title %}{% endblock %} | RealWorld Benchmark

RealWorld Benchmark

A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance.

{% block body %}{% endblock %}
PKê|>]À|Fi……$examples/rwbench/genshi/helpers.htmlnu„[µü¤
PKê|>]ôÚµRÅÅ"examples/rwbench/genshi/index.htmlnu„[µü¤ Index Page

${article.title}

written by ${article.user.username} on ${dateformat(article.pub_date)}

${Markup(article.body)}
Name
${input_field('name')}
E-Mail
${input_field('email')}
URL
${input_field('url')}
Comment
${textarea('comment')}
Captcha
${input_field('captcha')}
${input_field(type='submit', value='Submit')} ${input_field(name='cancel', type='submit', value='Cancel')}
PKê|>]CÍ�íí#examples/rwbench/genshi/layout.htmlnu„[µü¤ ${select('title/text()')} | RealWorld Benchmark

RealWorld Benchmark

A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance.

${select('*|text()')}
PKê|>]¹ÿ -»»#examples/rwbench/jinja/helpers.htmlnu„[µü¤{% macro input_field(name, value='', type='text') -%} {%- endmacro %} {% macro textarea(name, value='', rows=10, cols=40) -%} {%- endmacro %} {% macro form(action='', method='post') -%}
{{ caller() }}
{%- endmacro %} PKê|>]ðâáw!examples/rwbench/jinja/index.htmlnu„[µü¤{% extends "layout.html" %} {% from "helpers.html" import input_field, textarea, form %} {% block page_title %}Index Page{% endblock %} {% block body %} {%- for article in articles if article.published %}

{{ article.title|e }}

written by {{ article.user.username|e }} on {{ article.pub_date|dateformat }}

{{ article.body }}
{%- endfor %} {%- call form() %}
Name
{{ input_field('name') }}
E-Mail
{{ input_field('email') }}
URL
{{ input_field('url') }}
Comment
{{ textarea('comment') }}
Captcha
{{ input_field('captcha') }}
{{ input_field(type='submit', value='Submit') }} {{ input_field('cancel', type='submit', value='Cancel') }} {%- endcall %} {% endblock %} PKê|>]J­eúkk"examples/rwbench/jinja/layout.htmlnu„[µü¤ {% block page_title %}{% endblock %} | RealWorld Benchmark

RealWorld Benchmark

A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance.

{% block body %}{% endblock %}
PKê|>]€iËŒŒ"examples/rwbench/mako/helpers.htmlnu„[µü¤<%def name="input_field(name='', value='', type='text')"> <%def name="textarea(name, value='', rows=10, cols=40)"> <%def name="form(action='', method='post')">
${caller.body()}
PKê|>]ÆÎÎ examples/rwbench/mako/index.htmlnu„[µü¤<%! from rwbench import dateformat %> <%inherit file="layout.html" /> <%namespace file="helpers.html" import="input_field, textarea, form" /> <%def name="page_title()">Index Page % for article in articles: <% if not article.published: continue %>

${article.title|h}

written by ${article.user.username|h} on ${dateformat(article.pub_date)}

${article.body}
% endfor <%call expr="form()">
Name
${input_field('name')}
E-Mail
${input_field('email')}
URL
${input_field('url')}
Comment
${textarea('comment')}
Captcha
${input_field('captcha')}
${input_field(type='submit', value='Submit')} ${input_field(name='cancel', type='submit', value='Cancel')} PKê|>]?i^^!examples/rwbench/mako/layout.htmlnu„[µü¤ ${self.page_title()} | RealWorld Benchmark

RealWorld Benchmark

A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance.

${self.body()}
<%def name="page_title()"> PKê|>]` nƒÚÚexamples/rwbench/djangoext.pynu„[µü¤# -*- coding: utf-8 -*- from rwbench import ROOT from os.path import join from django.conf import settings settings.configure( TEMPLATE_DIRS=(join(ROOT, 'django'),), TEMPLATE_LOADERS=( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', )), ) ) from django.template import loader as django_loader, Context as DjangoContext, \ Node, NodeList, Variable, TokenParser from django import template as django_template_module from django.template import Library # for django extensions. We monkey patch our extensions in so that # we don't have to initialize a more complex django setup. django_extensions = django_template_module.Library() django_template_module.builtins.append(django_extensions) from rwbench import dateformat django_extensions.filter(dateformat) def var_or_none(x): if x is not None: return Variable(x) # and more django extensions @django_extensions.tag def input_field(parser, token): p = TokenParser(token.contents) args = [p.value()] while p.more(): args.append(p.value()) return InputFieldNode(*args) @django_extensions.tag def textarea(parser, token): p = TokenParser(token.contents) args = [p.value()] while p.more(): args.append(p.value()) return TextareaNode(*args) @django_extensions.tag def form(parser, token): p = TokenParser(token.contents) args = [] while p.more(): args.append(p.value()) body = parser.parse(('endform',)) parser.delete_first_token() return FormNode(body, *args) class InputFieldNode(Node): def __init__(self, name, type=None, value=None): self.name = var_or_none(name) self.type = var_or_none(type) self.value = var_or_none(value) def render(self, context): name = self.name.resolve(context) type = 'text' value = '' if self.type is not None: type = self.type.resolve(context) if self.value is not None: value = self.value.resolve(context) tmpl = django_loader.get_template('_input_field.html') return tmpl.render(DjangoContext({ 'name': name, 'type': type, 'value': value })) class TextareaNode(Node): def __init__(self, name, rows=None, cols=None, value=None): self.name = var_or_none(name) self.rows = var_or_none(rows) self.cols = var_or_none(cols) self.value = var_or_none(value) def render(self, context): name = self.name.resolve(context) rows = 10 cols = 40 value = '' if self.rows is not None: rows = int(self.rows.resolve(context)) if self.cols is not None: cols = int(self.cols.resolve(context)) if self.value is not None: value = self.value.resolve(context) tmpl = django_loader.get_template('_textarea.html') return tmpl.render(DjangoContext({ 'name': name, 'rows': rows, 'cols': cols, 'value': value })) class FormNode(Node): def __init__(self, body, action=None, method=None): self.body = body self.action = action self.method = method def render(self, context): body = self.body.render(context) action = '' method = 'post' if self.action is not None: action = self.action.resolve(context) if self.method is not None: method = self.method.resolve(context) tmpl = django_loader.get_template('_form.html') return tmpl.render(DjangoContext({ 'body': body, 'action': action, 'method': method })) PKê|>]Í'�  examples/rwbench/rwbench.pynu„[µü¤# -*- coding: utf-8 -*- """ RealWorldish Benchmark ~~~~~~~~~~~~~~~~~~~~~~ A more real-world benchmark of Jinja2. Like the other benchmark in the Jinja2 repository this has no real-world usefulnes (despite the name). Just go away and ignore it. NOW! :copyright: (c) 2009 by the Jinja Team. :license: BSD. """ import sys from os.path import join, dirname, abspath try: from cProfile import Profile except ImportError: from profile import Profile from pstats import Stats ROOT = abspath(dirname(__file__)) from random import choice, randrange from datetime import datetime from timeit import Timer from jinja2 import Environment, FileSystemLoader from jinja2.utils import generate_lorem_ipsum from mako.lookup import TemplateLookup from genshi.template import TemplateLoader as GenshiTemplateLoader def dateformat(x): return x.strftime('%Y-%m-%d') jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja'))) jinja_env.filters['dateformat'] = dateformat mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')]) genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')]) class Article(object): def __init__(self, id): self.id = id self.href = '/article/%d' % self.id self.title = generate_lorem_ipsum(1, False, 5, 10) self.user = choice(users) self.body = generate_lorem_ipsum() self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9)) self.published = True class User(object): def __init__(self, username): self.href = '/user/%s' % username self.username = username users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat']) articles = map(Article, range(20)) navigation = [ ('index', 'Index'), ('about', 'About'), ('foo?bar=1', 'Foo with Bar'), ('foo?bar=2&s=x', 'Foo with X'), ('blah', 'Blub Blah'), ('hehe', 'Haha'), ] * 5 context = dict(users=users, articles=articles, page_navigation=navigation) jinja_template = jinja_env.get_template('index.html') mako_template = mako_lookup.get_template('index.html') genshi_template = genshi_loader.load('index.html') def test_jinja(): jinja_template.render(context) def test_mako(): mako_template.render_unicode(**context) from djangoext import django_loader, DjangoContext def test_django(): # not cached because django is not thread safe and does # not cache by itself so it would be unfair to cache it here. django_template = django_loader.get_template('index.html') django_template.render(DjangoContext(context)) def test_genshi(): genshi_template.generate(**context).render('html', doctype='html') if __name__ == '__main__': sys.stdout.write('Realworldish Benchmark:\n') for test in 'jinja', 'mako', 'django', 'genshi': t = Timer(setup='from __main__ import test_%s as bench' % test, stmt='bench()') sys.stdout.write(' >> %-20s' % test) sys.stdout.flush() sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200)) if '-p' in sys.argv: print 'Jinja profile' p = Profile() p.runcall(test_jinja) stats = Stats(p) stats.sort_stats('time', 'calls') stats.print_stats() PKê|>]Ï+gæª*ª*examples/bench.pynu„[µü¤"""\ This benchmark compares some python templating engines with Jinja 2 so that we get a picture of how fast Jinja 2 is for a semi real world template. If a template engine is not installed the test is skipped.\ """ import sys import cgi from timeit import Timer from jinja2 import Environment as JinjaEnvironment context = { 'page_title': 'mitsuhiko\'s benchmark', 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] } jinja_template = JinjaEnvironment( line_statement_prefix='%', variable_start_string="${", variable_end_string="}" ).from_string("""\ ${page_title|e}

${page_title|e}

% for row in table % for cell in row % endfor % endfor
${cell}
\ """) def test_jinja(): jinja_template.render(context) try: from tornado.template import Template except ImportError: test_tornado = None else: tornado_template = Template("""\ {{ page_title }}

{{ page_title }}

{% for row in table %} {% for cell in row %} {% end %} {% end %}
{{ cell }}
\ """) def test_tornado(): tornado_template.generate(**context) try: from django.conf import settings settings.configure() from django.template import Template as DjangoTemplate, Context as DjangoContext except ImportError: test_django = None else: django_template = DjangoTemplate("""\ {{ page_title }}

{{ page_title }}

{% for row in table %} {% for cell in row %} {% endfor %} {% endfor %}
{{ cell }}
\ """) def test_django(): c = DjangoContext(context) c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')] django_template.render(c) try: from mako.template import Template as MakoTemplate except ImportError: test_mako = None else: mako_template = MakoTemplate("""\ ${page_title|h}

${page_title|h}

% for row in table: % for cell in row: % endfor % endfor
${cell}
\ """) def test_mako(): mako_template.render(**context) try: from genshi.template import MarkupTemplate as GenshiTemplate except ImportError: test_genshi = None else: genshi_template = GenshiTemplate("""\ ${page_title}

${page_title}

${cell}
\ """) def test_genshi(): genshi_template.generate(**context).render('html', strip_whitespace=False) try: from Cheetah.Template import Template as CheetahTemplate except ImportError: test_cheetah = None else: cheetah_template = CheetahTemplate("""\ #import cgi $cgi.escape($page_title)

$cgi.escape($page_title)

#for $row in $table: #for $cell in $row: #end for #end for
$cell
\ """, searchList=[dict(context)]) def test_cheetah(): unicode(cheetah_template) try: import tenjin except ImportError: test_tenjin = None else: tenjin_template = tenjin.Template() tenjin_template.convert("""\ ${page_title}

${page_title}

#{cell}
\ """) def test_tenjin(): from tenjin.helpers import escape, to_str tenjin_template.render(context, locals()) try: from spitfire.compiler import util as SpitfireTemplate from spitfire.compiler.analyzer import o2_options as spitfire_optimizer except ImportError: test_spitfire = None else: spitfire_template = SpitfireTemplate.load_template("""\ $cgi.escape($page_title)

$cgi.escape($page_title)

#for $row in $table #for $cell in $row #end for #end for
$cell
\ """, 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False}) spitfire_context = dict(context, **{'cgi': cgi}) def test_spitfire(): spitfire_template(search_list=[spitfire_context]).main() try: from chameleon.zpt.template import PageTemplate except ImportError: test_chameleon = None else: chameleon_template = PageTemplate("""\ Page Title

Page Title

cell
\ """) chameleon_context = dict(context) chameleon_context['sections'] = [ ('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products') ] def test_chameleon(): chameleon_template.render(**chameleon_context) try: from chameleon.zpt.template import PageTemplate from chameleon.genshi import language except ImportError: test_chameleon_genshi = None else: chameleon_genshi_template = PageTemplate("""\ ${page_title}

${page_title}

${row[cell]}
\ """, parser=language.Parser()) chameleon_genshi_context = dict(context) chameleon_genshi_context['sections'] = [ ('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products') ] def test_chameleon_genshi(): chameleon_genshi_template.render(**chameleon_genshi_context) sys.stdout.write('\r' + '\n'.join(( '=' * 80, 'Template Engine BigTable Benchmark'.center(80), '=' * 80, __doc__, '-' * 80 )) + '\n') for test in 'jinja', 'mako', 'tornado', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah', 'chameleon', 'chameleon_genshi': if locals()['test_' + test] is None: sys.stdout.write(' %-20s*not installed*\n' % test) continue t = Timer(setup='from __main__ import test_%s as bench' % test, stmt='bench()') sys.stdout.write(' >> %-20s' % test) sys.stdout.flush() sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50)) sys.stdout.write('-' * 80 + '\n') sys.stdout.write('''\ WARNING: The results of this benchmark are useless to compare the performance of template engines and should not be taken seriously in any way. It's testing the performance of simple loops and has no real-world usefulnes. It only used to check if changes on the Jinja code affect performance in a good or bad way and how it roughly compares to others. ''' + '=' * 80 + '\n') PKê|>]SAxýSSexamples/profile.pynu„[µü¤try: from cProfile import Profile except ImportError: from profile import Profile from pstats import Stats from jinja2 import Environment as JinjaEnvironment context = { 'page_title': 'mitsuhiko\'s benchmark', 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] } source = """\ % macro testmacro(x) ${x} % endmacro ${page_title|e}

${page_title|e}

% for row in table % for cell in row % endfor % endfor
${testmacro(cell)}
\ """ jinja_template = JinjaEnvironment( line_statement_prefix='%', variable_start_string="${", variable_end_string="}" ).from_string(source) print jinja_template.environment.compile(source, raw=True) p = Profile() p.runcall(lambda: jinja_template.render(context)) stats = Stats(p) stats.sort_stats('time', 'calls') stats.print_stats() PKê|>]‰3ä?ext/Vim/jinja.vimnu„[µü¤" Vim syntax file " Language: Jinja template " Maintainer: Armin Ronacher " Last Change: 2008 May 9 " Version: 1.1 " " Known Bugs: " because of odd limitations dicts and the modulo operator " appear wrong in the template. " " Changes: " " 2008 May 9: Added support for Jinja2 changes (new keyword rules) " .vimrc variable to disable html highlighting if !exists('g:jinja_syntax_html') let g:jinja_syntax_html=1 endif " For version 5.x: Clear all syntax items " For version 6.x: Quit when a syntax file was already loaded if !exists("main_syntax") if version < 600 syntax clear elseif exists("b:current_syntax") finish endif let main_syntax = 'jinja' endif " Pull in the HTML syntax. if g:jinja_syntax_html if version < 600 so :p:h/html.vim else runtime! syntax/html.vim unlet b:current_syntax endif endif syntax case match " Jinja template built-in tags and parameters (without filter, macro, is and raw, they " have special threatment) syn keyword jinjaStatement containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained and if else in not or recursive as import syn keyword jinjaStatement containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained is filter skipwhite nextgroup=jinjaFilter syn keyword jinjaStatement containedin=jinjaTagBlock contained macro skipwhite nextgroup=jinjaFunction syn keyword jinjaStatement containedin=jinjaTagBlock contained block skipwhite nextgroup=jinjaBlockName " Variable Names syn match jinjaVariable containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[a-zA-Z_][a-zA-Z0-9_]*/ syn keyword jinjaSpecial containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained false true none False True None loop super caller varargs kwargs " Filters syn match jinjaOperator "|" containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained skipwhite nextgroup=jinjaFilter syn match jinjaFilter contained /[a-zA-Z_][a-zA-Z0-9_]*/ syn match jinjaFunction contained /[a-zA-Z_][a-zA-Z0-9_]*/ syn match jinjaBlockName contained /[a-zA-Z_][a-zA-Z0-9_]*/ " Jinja template constants syn region jinjaString containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained start=/"/ skip=/\(\\\)\@\)*\\"/ end=/"/ syn region jinjaString containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained start=/'/ skip=/\(\\\)\@\)*\\'/ end=/'/ syn match jinjaNumber containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[0-9]\+\(\.[0-9]\+\)\?/ " Operators syn match jinjaOperator containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[+\-*\/<>=!,:]/ syn match jinjaPunctuation containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[()\[\]]/ syn match jinjaOperator containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /\./ nextgroup=jinjaAttribute syn match jinjaAttribute contained /[a-zA-Z_][a-zA-Z0-9_]*/ " Jinja template tag and variable blocks syn region jinjaNested matchgroup=jinjaOperator start="(" end=")" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained syn region jinjaNested matchgroup=jinjaOperator start="\[" end="\]" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained syn region jinjaNested matchgroup=jinjaOperator start="{" end="}" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained syn region jinjaTagBlock matchgroup=jinjaTagDelim start=/{%-\?/ end=/-\?%}/ containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaRaw,jinjaString,jinjaNested,jinjaComment syn region jinjaVarBlock matchgroup=jinjaVarDelim start=/{{-\?/ end=/-\?}}/ containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaRaw,jinjaString,jinjaNested,jinjaComment " Jinja template 'raw' tag syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment " Jinja comments syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment " Block start keywords. A bit tricker. We only highlight at the start of a " tag block and only if the name is not followed by a comma or equals sign " which usually means that we have to deal with an assignment. syn match jinjaStatement containedin=jinjaTagBlock contained /\({%-\?\s*\)\@<=\<[a-zA-Z_][a-zA-Z0-9_]*\>\(\s*[,=]\)\@!/ " and context modifiers syn match jinjaStatement containedin=jinjaTagBlock contained /\/ " Define the default highlighting. " For version 5.7 and earlier: only when not done already " For version 5.8 and later: only when an item doesn't have highlighting yet if version >= 508 || !exists("did_jinja_syn_inits") if version < 508 let did_jinja_syn_inits = 1 command -nargs=+ HiLink hi link else command -nargs=+ HiLink hi def link endif HiLink jinjaPunctuation jinjaOperator HiLink jinjaAttribute jinjaVariable HiLink jinjaFunction jinjaFilter HiLink jinjaTagDelim jinjaTagBlock HiLink jinjaVarDelim jinjaVarBlock HiLink jinjaCommentDelim jinjaComment HiLink jinjaRawDelim jinja HiLink jinjaSpecial Special HiLink jinjaOperator Normal HiLink jinjaRaw Normal HiLink jinjaTagBlock PreProc HiLink jinjaVarBlock PreProc HiLink jinjaStatement Statement HiLink jinjaFilter Function HiLink jinjaBlockName Function HiLink jinjaVariable Identifier HiLink jinjaString Constant HiLink jinjaNumber Constant HiLink jinjaComment Comment delcommand HiLink endif let b:current_syntax = "jinja" if main_syntax == 'jinja' unlet main_syntax endif PKê|>]ñ3Kèôô%ext/django2jinja/templates/index.htmlnu„[µü¤{% extends "layout.html" %} {% load i18n %} {% block title %}Foo{% endblock %} {% block page-body %} {{ block.super }} Hello {{ name|cut:"d" }}! {% for item in seq reversed %} {% if forloop.index|divisibleby:2 %}
  • {{ item }}
  • {% endif %} {% endfor %} {% ifequal foo bar %} haha {% else %} hmm {% endifequal %} {% filter upper %} {% include "subtemplate.html" %} {% include foo %} {% endfilter %} {% spaceless %} Hello World {{ foo }} Hmm {% endspaceless %} {% templatetag opencomment %}...{% templatetag closecomment %} {% url foo a, b, c=d %} {% url foo a, b, c=d as hmm %} {% with object.value as value %} {% endwith %}
    {% debug %}
    {% blocktrans with book|title as book_t and author|title as author_t %} This is {{ book_t }} by {{ author_t }} {% endblocktrans %} {% blocktrans count list|length as counter %} There is only one {{ name }} object. {% plural %} There are {{ counter }} {{ name }} objects. {% endblocktrans %} {% blocktrans with name|escape as name count list|length as counter %} There is only one {{ name }} object. {% plural %} There are {{ counter }} {{ name }} objects. {% endblocktrans %} {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}

    {% trans "This is the title." %}

    {% regroup people by gender as grouped %} {% endblock %} PKê|>] #|aoo&ext/django2jinja/templates/layout.htmlnu„[µü¤{% block title %}{% endblock %}
    {% block page-body %}{% endblock %}
    PKê|>]ÝÝ} +ext/django2jinja/templates/subtemplate.htmlnu„[µü¤Hello World! PKê|>]Q`O|§`§` ext/django2jinja/django2jinja.pynu„[µü¤# -*- coding: utf-8 -*- """ Django to Jinja ~~~~~~~~~~~~~~~ Helper module that can convert django templates into Jinja2 templates. This file is not intended to be used as stand alone application but to be used as library. To convert templates you basically create your own writer, add extra conversion logic for your custom template tags, configure your django environment and run the `convert_templates` function. Here a simple example:: # configure django (or use settings.configure) import os os.environ['DJANGO_SETTINGS_MODULE'] = 'yourapplication.settings' from yourapplication.foo.templatetags.bar import MyNode from django2jinja import Writer, convert_templates def write_my_node(writer, node): writer.start_variable() writer.write('myfunc(') for idx, arg in enumerate(node.args): if idx: writer.write(', ') writer.node(arg) writer.write(')') writer.end_variable() writer = Writer() writer.node_handlers[MyNode] = write_my_node convert_templates('/path/to/output/folder', writer=writer) Here is an example hos to automatically translate your django variables to jinja2:: import re # List of tuple (Match pattern, Replace pattern, Exclusion pattern) var_re = ((re.compile(r"(u|user)\.is_authenticated"), r"\1.is_authenticated()", None), (re.compile(r"\.non_field_errors"), r".non_field_errors()", None), (re.compile(r"\.label_tag"), r".label_tag()", None), (re.compile(r"\.as_dl"), r".as_dl()", None), (re.compile(r"\.as_table"), r".as_table()", None), (re.compile(r"\.as_widget"), r".as_widget()", None), (re.compile(r"\.as_hidden"), r".as_hidden()", None), (re.compile(r"\.get_([0-9_\w]+)_url"), r".get_\1_url()", None), (re.compile(r"\.url"), r".url()", re.compile(r"(form|calendar).url")), (re.compile(r"\.get_([0-9_\w]+)_display"), r".get_\1_display()", None), (re.compile(r"loop\.counter"), r"loop.index", None), (re.compile(r"loop\.revcounter"), r"loop.revindex", None), (re.compile(r"request\.GET\.([0-9_\w]+)"), r"request.GET.get('\1', '')", None), (re.compile(r"request\.get_host"), r"request.get_host()", None), (re.compile(r"\.all(?!_)"), r".all()", None), (re.compile(r"\.all\.0"), r".all()[0]", None), (re.compile(r"\.([0-9])($|\s+)"), r"[\1]\2", None), (re.compile(r"\.items"), r".items()", None), ) writer = Writer(var_re=var_re) For details about the writing process have a look at the module code. :copyright: (c) 2009 by the Jinja Team. :license: BSD. """ import re import os import sys from jinja2.defaults import * from django.conf import settings from django.template import defaulttags as core_tags, loader, TextNode, \ FilterExpression, libraries, Variable, loader_tags, TOKEN_TEXT, \ TOKEN_VAR from django.template.debug import DebugVariableNode as VariableNode from django.templatetags import i18n as i18n_tags from StringIO import StringIO _node_handlers = {} _resolved_filters = {} _newline_re = re.compile(r'(?:\r\n|\r|\n)') # Django stores an itertools object on the cycle node. Not only is this # thread unsafe but also a problem for the converter which needs the raw # string values passed to the constructor to create a jinja loop.cycle() # call from it. _old_cycle_init = core_tags.CycleNode.__init__ def _fixed_cycle_init(self, cyclevars, variable_name=None): self.raw_cycle_vars = map(Variable, cyclevars) _old_cycle_init(self, cyclevars, variable_name) core_tags.CycleNode.__init__ = _fixed_cycle_init def node(cls): def proxy(f): _node_handlers[cls] = f return f return proxy def convert_templates(output_dir, extensions=('.html', '.txt'), writer=None, callback=None): """Iterates over all templates in the template dirs configured and translates them and writes the new templates into the output directory. """ if writer is None: writer = Writer() def filter_templates(files): for filename in files: ifilename = filename.lower() for extension in extensions: if ifilename.endswith(extension): yield filename def translate(f, loadname): template = loader.get_template(loadname) original = writer.stream writer.stream = f writer.body(template.nodelist) writer.stream = original if callback is None: def callback(template): print template for directory in settings.TEMPLATE_DIRS: for dirname, _, files in os.walk(directory): dirname = dirname[len(directory) + 1:] for filename in filter_templates(files): source = os.path.normpath(os.path.join(dirname, filename)) target = os.path.join(output_dir, dirname, filename) basetarget = os.path.dirname(target) if not os.path.exists(basetarget): os.makedirs(basetarget) callback(source) f = file(target, 'w') try: translate(f, source) finally: f.close() class Writer(object): """The core writer class.""" def __init__(self, stream=None, error_stream=None, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, initial_autoescape=True, use_jinja_autoescape=False, custom_node_handlers=None, var_re=[], env=None): if stream is None: stream = sys.stdout if error_stream is None: error_stream = sys.stderr self.stream = stream self.error_stream = error_stream self.block_start_string = block_start_string self.block_end_string = block_end_string self.variable_start_string = variable_start_string self.variable_end_string = variable_end_string self.comment_start_string = comment_start_string self.comment_end_string = comment_end_string self.autoescape = initial_autoescape self.spaceless = False self.use_jinja_autoescape = use_jinja_autoescape self.node_handlers = dict(_node_handlers, **(custom_node_handlers or {})) self._loop_depth = 0 self._filters_warned = set() self.var_re = var_re self.env = env def enter_loop(self): """Increments the loop depth so that write functions know if they are in a loop. """ self._loop_depth += 1 def leave_loop(self): """Reverse of enter_loop.""" self._loop_depth -= 1 @property def in_loop(self): """True if we are in a loop.""" return self._loop_depth > 0 def write(self, s): """Writes stuff to the stream.""" self.stream.write(s.encode(settings.FILE_CHARSET)) def print_expr(self, expr): """Open a variable tag, write to the string to the stream and close.""" self.start_variable() self.write(expr) self.end_variable() def _post_open(self): if self.spaceless: self.write('- ') else: self.write(' ') def _pre_close(self): if self.spaceless: self.write(' -') else: self.write(' ') def start_variable(self): """Start a variable.""" self.write(self.variable_start_string) self._post_open() def end_variable(self, always_safe=False): """End a variable.""" if not always_safe and self.autoescape and \ not self.use_jinja_autoescape: self.write('|e') self._pre_close() self.write(self.variable_end_string) def start_block(self): """Starts a block.""" self.write(self.block_start_string) self._post_open() def end_block(self): """Ends a block.""" self._pre_close() self.write(self.block_end_string) def tag(self, name): """Like `print_expr` just for blocks.""" self.start_block() self.write(name) self.end_block() def variable(self, name): """Prints a variable. This performs variable name transformation.""" self.write(self.translate_variable_name(name)) def literal(self, value): """Writes a value as literal.""" value = repr(value) if value[:2] in ('u"', "u'"): value = value[1:] self.write(value) def filters(self, filters, is_block=False): """Dumps a list of filters.""" want_pipe = not is_block for filter, args in filters: name = self.get_filter_name(filter) if name is None: self.warn('Could not find filter %s' % name) continue if name not in DEFAULT_FILTERS and \ name not in self._filters_warned: self._filters_warned.add(name) self.warn('Filter %s probably doesn\'t exist in Jinja' % name) if not want_pipe: want_pipe = True else: self.write('|') self.write(name) if args: self.write('(') for idx, (is_var, value) in enumerate(args): if idx: self.write(', ') if is_var: self.node(value) else: self.literal(value) self.write(')') def get_location(self, origin, position): """Returns the location for an origin and position tuple as name and lineno. """ if hasattr(origin, 'source'): source = origin.source name = '' else: source = origin.loader(origin.loadname, origin.dirs)[0] name = origin.loadname lineno = len(_newline_re.findall(source[:position[0]])) + 1 return name, lineno def warn(self, message, node=None): """Prints a warning to the error stream.""" if node is not None and hasattr(node, 'source'): filename, lineno = self.get_location(*node.source) message = '[%s:%d] %s' % (filename, lineno, message) print >> self.error_stream, message def translate_variable_name(self, var): """Performs variable name translation.""" if self.in_loop and var == 'forloop' or var.startswith('forloop.'): var = var[3:] for reg, rep, unless in self.var_re: no_unless = unless and unless.search(var) or True if reg.search(var) and no_unless: var = reg.sub(rep, var) break return var def get_filter_name(self, filter): """Returns the filter name for a filter function or `None` if there is no such filter. """ if filter not in _resolved_filters: for library in libraries.values(): for key, value in library.filters.iteritems(): _resolved_filters[value] = key return _resolved_filters.get(filter, None) def node(self, node): """Invokes the node handler for a node.""" for cls, handler in self.node_handlers.iteritems(): if type(node) is cls or type(node).__name__ == cls: handler(self, node) break else: self.warn('Untranslatable node %s.%s found' % ( node.__module__, node.__class__.__name__ ), node) def body(self, nodes): """Calls node() for every node in the iterable passed.""" for node in nodes: self.node(node) @node(TextNode) def text_node(writer, node): writer.write(node.s) @node(Variable) def variable(writer, node): if node.translate: writer.warn('i18n system used, make sure to install translations', node) writer.write('_(') if node.literal is not None: writer.literal(node.literal) else: writer.variable(node.var) if node.translate: writer.write(')') @node(VariableNode) def variable_node(writer, node): writer.start_variable() if node.filter_expression.var.var == 'block.super' \ and not node.filter_expression.filters: writer.write('super()') else: writer.node(node.filter_expression) writer.end_variable() @node(FilterExpression) def filter_expression(writer, node): writer.node(node.var) writer.filters(node.filters) @node(core_tags.CommentNode) def comment_tag(writer, node): pass @node(core_tags.DebugNode) def comment_tag(writer, node): writer.warn('Debug tag detected. Make sure to add a global function ' 'called debug to the namespace.', node=node) writer.print_expr('debug()') @node(core_tags.ForNode) def for_loop(writer, node): writer.start_block() writer.write('for ') for idx, var in enumerate(node.loopvars): if idx: writer.write(', ') writer.variable(var) writer.write(' in ') if node.is_reversed: writer.write('(') writer.node(node.sequence) if node.is_reversed: writer.write(')|reverse') writer.end_block() writer.enter_loop() writer.body(node.nodelist_loop) writer.leave_loop() writer.tag('endfor') @node(core_tags.IfNode) def if_condition(writer, node): writer.start_block() writer.write('if ') join_with = 'and' if node.link_type == core_tags.IfNode.LinkTypes.or_: join_with = 'or' for idx, (ifnot, expr) in enumerate(node.bool_exprs): if idx: writer.write(' %s ' % join_with) if ifnot: writer.write('not ') writer.node(expr) writer.end_block() writer.body(node.nodelist_true) if node.nodelist_false: writer.tag('else') writer.body(node.nodelist_false) writer.tag('endif') @node(core_tags.IfEqualNode) def if_equal(writer, node): writer.start_block() writer.write('if ') writer.node(node.var1) if node.negate: writer.write(' != ') else: writer.write(' == ') writer.node(node.var2) writer.end_block() writer.body(node.nodelist_true) if node.nodelist_false: writer.tag('else') writer.body(node.nodelist_false) writer.tag('endif') @node(loader_tags.BlockNode) def block(writer, node): writer.tag('block ' + node.name.replace('-', '_').rstrip('_')) node = node while node.parent is not None: node = node.parent writer.body(node.nodelist) writer.tag('endblock') @node(loader_tags.ExtendsNode) def extends(writer, node): writer.start_block() writer.write('extends ') if node.parent_name_expr: writer.node(node.parent_name_expr) else: writer.literal(node.parent_name) writer.end_block() writer.body(node.nodelist) @node(loader_tags.ConstantIncludeNode) @node(loader_tags.IncludeNode) def include(writer, node): writer.start_block() writer.write('include ') if hasattr(node, 'template'): writer.literal(node.template.name) else: writer.node(node.template_name) writer.end_block() @node(core_tags.CycleNode) def cycle(writer, node): if not writer.in_loop: writer.warn('Untranslatable free cycle (cycle outside loop)', node=node) return if node.variable_name is not None: writer.start_block() writer.write('set %s = ' % node.variable_name) else: writer.start_variable() writer.write('loop.cycle(') for idx, var in enumerate(node.raw_cycle_vars): if idx: writer.write(', ') writer.node(var) writer.write(')') if node.variable_name is not None: writer.end_block() else: writer.end_variable() @node(core_tags.FilterNode) def filter(writer, node): writer.start_block() writer.write('filter ') writer.filters(node.filter_expr.filters, True) writer.end_block() writer.body(node.nodelist) writer.tag('endfilter') @node(core_tags.AutoEscapeControlNode) def autoescape_control(writer, node): original = writer.autoescape writer.autoescape = node.setting writer.body(node.nodelist) writer.autoescape = original @node(core_tags.SpacelessNode) def spaceless(writer, node): original = writer.spaceless writer.spaceless = True writer.warn('entering spaceless mode with different semantics', node) # do the initial stripping nodelist = list(node.nodelist) if nodelist: if isinstance(nodelist[0], TextNode): nodelist[0] = TextNode(nodelist[0].s.lstrip()) if isinstance(nodelist[-1], TextNode): nodelist[-1] = TextNode(nodelist[-1].s.rstrip()) writer.body(nodelist) writer.spaceless = original @node(core_tags.TemplateTagNode) def template_tag(writer, node): tag = { 'openblock': writer.block_start_string, 'closeblock': writer.block_end_string, 'openvariable': writer.variable_start_string, 'closevariable': writer.variable_end_string, 'opencomment': writer.comment_start_string, 'closecomment': writer.comment_end_string, 'openbrace': '{', 'closebrace': '}' }.get(node.tagtype) if tag: writer.start_variable() writer.literal(tag) writer.end_variable() @node(core_tags.URLNode) def url_tag(writer, node): writer.warn('url node used. make sure to provide a proper url() ' 'function', node) if node.asvar: writer.start_block() writer.write('set %s = ' % node.asvar) else: writer.start_variable() autoescape = writer.autoescape writer.write('url(') writer.literal(node.view_name) for arg in node.args: writer.write(', ') writer.node(arg) for key, arg in node.kwargs.items(): writer.write(', %s=' % key) writer.node(arg) writer.write(')') if node.asvar: writer.end_block() else: writer.end_variable() @node(core_tags.WidthRatioNode) def width_ratio(writer, node): writer.warn('widthratio expanded into formula. You may want to provide ' 'a helper function for this calculation', node) writer.start_variable() writer.write('(') writer.node(node.val_expr) writer.write(' / ') writer.node(node.max_expr) writer.write(' * ') writer.write(str(int(node.max_width))) writer.write(')|round|int') writer.end_variable(always_safe=True) @node(core_tags.WithNode) def with_block(writer, node): writer.warn('with block expanded into set statement. This could cause ' 'variables following that block to be overridden.', node) writer.start_block() writer.write('set %s = ' % node.name) writer.node(node.var) writer.end_block() writer.body(node.nodelist) @node(core_tags.RegroupNode) def regroup(writer, node): if node.expression.var.literal: writer.warn('literal in groupby filter used. Behavior in that ' 'situation is undefined and translation is skipped.', node) return elif node.expression.filters: writer.warn('filters in groupby filter used. Behavior in that ' 'situation is undefined which is most likely a bug ' 'in your code. Filters were ignored.', node) writer.start_block() writer.write('set %s = ' % node.var_name) writer.node(node.target) writer.write('|groupby(') writer.literal(node.expression.var.var) writer.write(')') writer.end_block() @node(core_tags.LoadNode) def warn_load(writer, node): writer.warn('load statement used which was ignored on conversion', node) @node(i18n_tags.GetAvailableLanguagesNode) def get_available_languages(writer, node): writer.warn('make sure to provide a get_available_languages function', node) writer.tag('set %s = get_available_languages()' % writer.translate_variable_name(node.variable)) @node(i18n_tags.GetCurrentLanguageNode) def get_current_language(writer, node): writer.warn('make sure to provide a get_current_language function', node) writer.tag('set %s = get_current_language()' % writer.translate_variable_name(node.variable)) @node(i18n_tags.GetCurrentLanguageBidiNode) def get_current_language_bidi(writer, node): writer.warn('make sure to provide a get_current_language_bidi function', node) writer.tag('set %s = get_current_language_bidi()' % writer.translate_variable_name(node.variable)) @node(i18n_tags.TranslateNode) def simple_gettext(writer, node): writer.warn('i18n system used, make sure to install translations', node) writer.start_variable() writer.write('_(') writer.node(node.value) writer.write(')') writer.end_variable() @node(i18n_tags.BlockTranslateNode) def translate_block(writer, node): first_var = [] variables = set() def touch_var(name): variables.add(name) if not first_var: first_var.append(name) def dump_token_list(tokens): for token in tokens: if token.token_type == TOKEN_TEXT: writer.write(token.contents) elif token.token_type == TOKEN_VAR: writer.print_expr(token.contents) touch_var(token.contents) writer.warn('i18n system used, make sure to install translations', node) writer.start_block() writer.write('trans') idx = -1 for idx, (key, var) in enumerate(node.extra_context.items()): if idx: writer.write(',') writer.write(' %s=' % key) touch_var(key) writer.node(var.filter_expression) have_plural = False plural_var = None if node.plural and node.countervar and node.counter: have_plural = True plural_var = node.countervar if plural_var not in variables: if idx > -1: writer.write(',') touch_var(plural_var) writer.write(' %s=' % plural_var) writer.node(node.counter) writer.end_block() dump_token_list(node.singular) if node.plural and node.countervar and node.counter: writer.start_block() writer.write('pluralize') if node.countervar != first_var[0]: writer.write(' ' + node.countervar) writer.end_block() dump_token_list(node.plural) writer.tag('endtrans') @node("SimpleNode") def simple_tag(writer, node): """Check if the simple tag exist as a filter in """ name = node.tag_name if writer.env and \ name not in writer.env.filters and \ name not in writer._filters_warned: writer._filters_warned.add(name) writer.warn('Filter %s probably doesn\'t exist in Jinja' % name) if not node.vars_to_resolve: # No argument, pass the request writer.start_variable() writer.write('request|') writer.write(name) writer.end_variable() return first_var = node.vars_to_resolve[0] args = node.vars_to_resolve[1:] writer.start_variable() # Copied from Writer.filters() writer.node(first_var) writer.write('|') writer.write(name) if args: writer.write('(') for idx, var in enumerate(args): if idx: writer.write(', ') if var.var: writer.node(var) else: writer.literal(var.literal) writer.write(')') writer.end_variable() # get rid of node now, it shouldn't be used normally del node PKê|>]Ë«  ôôext/django2jinja/example.pynu„[µü¤from django.conf import settings settings.configure(TEMPLATE_DIRS=['templates'], TEMPLATE_DEBUG=True) from django2jinja import convert_templates, Writer writer = Writer(use_jinja_autoescape=True) convert_templates('converted', writer=writer) PKê|>]·ÛTöµ µ ext/djangojinja2.pynu„[µü¤# -*- coding: utf-8 -*- """ djangojinja2 ~~~~~~~~~~~~ Adds support for Jinja2 to Django. Configuration variables: ======================= ============================================= Key Description ======================= ============================================= `JINJA2_TEMPLATE_DIRS` List of template folders `JINJA2_EXTENSIONS` List of Jinja2 extensions to use `JINJA2_CACHE_SIZE` The size of the Jinja2 template cache. ======================= ============================================= :copyright: (c) 2009 by the Jinja Team. :license: BSD. """ from itertools import chain from django.conf import settings from django.http import HttpResponse from django.core.exceptions import ImproperlyConfigured from django.template.context import get_standard_processors from django.template import TemplateDoesNotExist from jinja2 import Environment, FileSystemLoader, TemplateNotFound from jinja2.defaults import DEFAULT_NAMESPACE # the environment is unconfigured until the first template is loaded. _jinja_env = None def get_env(): """Get the Jinja2 env and initialize it if necessary.""" global _jinja_env if _jinja_env is None: _jinja_env = create_env() return _jinja_env def create_env(): """Create a new Jinja2 environment.""" searchpath = list(settings.JINJA2_TEMPLATE_DIRS) return Environment(loader=FileSystemLoader(searchpath), auto_reload=settings.TEMPLATE_DEBUG, cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 400), extensions=getattr(settings, 'JINJA2_EXTENSIONS', ())) def get_template(template_name, globals=None): """Load a template.""" try: return get_env().get_template(template_name, globals=globals) except TemplateNotFound, e: raise TemplateDoesNotExist(str(e)) def select_template(templates, globals=None): """Try to load one of the given templates.""" env = get_env() for template in templates: try: return env.get_template(template, globals=globals) except TemplateNotFound: continue raise TemplateDoesNotExist(', '.join(templates)) def render_to_string(template_name, context=None, request=None, processors=None): """Render a template into a string.""" context = dict(context or {}) if request is not None: context['request'] = request for processor in chain(get_standard_processors(), processors or ()): context.update(processor(request)) return get_template(template_name).render(context) def render_to_response(template_name, context=None, request=None, processors=None, mimetype=None): """Render a template into a response object.""" return HttpResponse(render_to_string(template_name, context, request, processors), mimetype=mimetype) PKê|>]x·_O? ? ext/inlinegettext.pynu„[µü¤# -*- coding: utf-8 -*- """ Inline Gettext ~~~~~~~~~~~~~~ An example extension for Jinja2 that supports inline gettext calls. Requires the i18n extension to be loaded. :copyright: (c) 2009 by the Jinja Team. :license: BSD. """ import re from jinja2.ext import Extension from jinja2.lexer import Token, count_newlines from jinja2.exceptions import TemplateSyntaxError _outside_re = re.compile(r'\\?(gettext|_)\(') _inside_re = re.compile(r'\\?[()]') class InlineGettext(Extension): """This extension implements support for inline gettext blocks::

    _(Welcome)

    _(This is a paragraph)

    Requires the i18n extension to be loaded and configured. """ def filter_stream(self, stream): paren_stack = 0 for token in stream: if token.type is not 'data': yield token continue pos = 0 lineno = token.lineno while 1: if not paren_stack: match = _outside_re.search(token.value, pos) else: match = _inside_re.search(token.value, pos) if match is None: break new_pos = match.start() if new_pos > pos: preval = token.value[pos:new_pos] yield Token(lineno, 'data', preval) lineno += count_newlines(preval) gtok = match.group() if gtok[0] == '\\': yield Token(lineno, 'data', gtok[1:]) elif not paren_stack: yield Token(lineno, 'block_begin', None) yield Token(lineno, 'name', 'trans') yield Token(lineno, 'block_end', None) paren_stack = 1 else: if gtok == '(' or paren_stack > 1: yield Token(lineno, 'data', gtok) paren_stack += gtok == ')' and -1 or 1 if not paren_stack: yield Token(lineno, 'block_begin', None) yield Token(lineno, 'name', 'endtrans') yield Token(lineno, 'block_end', None) pos = match.end() if pos < len(token.value): yield Token(lineno, 'data', token.value[pos:]) if paren_stack: raise TemplateSyntaxError('unclosed gettext expression', token.lineno, stream.name, stream.filename) PKê|>]¦ÕÔØ}} ext/jinja.elnu„[µü¤;;; jinja.el --- Jinja mode highlighting ;; ;; Author: Georg Brandl ;; Copyright: (c) 2009 by the Jinja Team ;; Last modified: 2008-05-22 23:04 by gbr ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; Commentary: ;; ;; Mostly ripped off django-mode by Lennart Borgman. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; This program is free software; you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation; either version 2, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth ;; Floor, Boston, MA 02110-1301, USA. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; Code: (defconst jinja-font-lock-keywords (list ; (cons (rx "{% comment %}" (submatch (0+ anything)) ; "{% endcomment %}") (list 1 font-lock-comment-face)) '("{# ?\\(.*?\\) ?#}" . (1 font-lock-comment-face)) '("{%-?\\|-?%}\\|{{\\|}}" . font-lock-preprocessor-face) '("{#\\|#}" . font-lock-comment-delimiter-face) ;; first word in a block is a command '("{%-?[ \t\n]*\\([a-zA-Z_]+\\)" . (1 font-lock-keyword-face)) ;; variables '("\\({{ ?\\)\\([^|]*?\\)\\(|.*?\\)? ?}}" . (1 font-lock-variable-name-face)) ;; keywords and builtins (cons (rx word-start (or "in" "as" "recursive" "not" "and" "or" "if" "else" "import" "with" "without" "context") word-end) font-lock-keyword-face) (cons (rx word-start (or "true" "false" "none" "loop" "self" "super") word-end) font-lock-builtin-face) ;; tests '("\\(is\\)[ \t]*\\(not\\)[ \t]*\\([a-zA-Z_]+\\)" (1 font-lock-keyword-face) (2 font-lock-keyword-face) (3 font-lock-function-name-face)) ;; builtin filters (cons (rx "|" (* space) (submatch (or "abs" "batch" "capitalize" "capture" "center" "count" "default" "dformat" "dictsort" "e" "escape" "filesizeformat" "first" "float" "format" "getattribute" "getitem" "groupby" "indent" "int" "join" "jsonencode" "last" "length" "lower" "markdown" "pprint" "random" "replace" "reverse" "round" "rst" "slice" "sort" "string" "striptags" "sum" "textile" "title" "trim" "truncate" "upper" "urlencode" "urlize" "wordcount" "wordwrap" "xmlattr"))) (list 1 font-lock-builtin-face)) ) "Minimal highlighting expressions for Jinja mode") (define-derived-mode jinja-mode nil "Jinja" "Simple Jinja mode for use with `mumamo-mode'. This mode only provides syntax highlighting." ;;(set (make-local-variable 'comment-start) "{#") ;;(set (make-local-variable 'comment-end) "#}") (setq font-lock-defaults '(jinja-font-lock-keywords))) ;; mumamo stuff (when (require 'mumamo nil t) (defun mumamo-chunk-jinja3 (pos max) "Find {# ... #}" (mumamo-quick-chunk-forward pos max "{#" "#}" 'borders 'jinja-mode)) (defun mumamo-chunk-jinja2 (pos max) "Find {{ ... }}" (mumamo-quick-chunk-forward pos max "{{" "}}" 'borders 'jinja-mode)) (defun mumamo-chunk-jinja (pos max) "Find {% ... %}" (mumamo-quick-chunk-forward pos max "{%" "%}" 'borders 'jinja-mode)) ;;;###autoload (define-mumamo-multi-major-mode jinja-html-mumamo "Turn on multiple major modes for Jinja with main mode `html-mode'. This also covers inlined style and javascript." ("Jinja HTML Family" html-mode (mumamo-chunk-jinja mumamo-chunk-jinja2 mumamo-chunk-jinja3 mumamo-chunk-inlined-style mumamo-chunk-inlined-script mumamo-chunk-style= mumamo-chunk-onjs= ))) ;;;###autoload (define-mumamo-multi-major-mode jinja-nxhtml-mumamo "Turn on multiple major modes for Jinja with main mode `nxhtml-mode'. This also covers inlined style and javascript." ("Jinja nXhtml Family" nxhtml-mode (mumamo-chunk-jinja mumamo-chunk-jinja2 mumamo-chunk-jinja3 mumamo-chunk-inlined-style mumamo-chunk-inlined-script mumamo-chunk-style= mumamo-chunk-onjs= ))) ) (provide 'jinja) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; jinja.el ends here PKê|>]l6 C@‚@‚html/_sources/api.rst.txtnu„[µü¤API === .. module:: jinja2 :synopsis: public Jinja2 API This document describes the API to Jinja2 and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Jinja2 templates. Basics ------ Jinja2 uses a central object called the template :class:`Environment`. Instances of this class are used to store the configuration and global objects, and are used to load templates from the file system or other locations. Even if you are creating templates from strings by using the constructor of :class:`Template` class, an environment is created automatically for you, albeit a shared one. Most applications will create one :class:`Environment` object on application initialization and use that to load templates. In some cases however, it's useful to have multiple environments side by side, if different configurations are in use. The simplest way to configure Jinja2 to load templates for your application looks roughly like this:: from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader('yourapplication', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) This will create a template environment with the default settings and a loader that looks up the templates in the `templates` folder inside the `yourapplication` python package. Different loaders are available and you can also write your own if you want to load templates from a database or other resources. This also enables autoescaping for HTML and XML files. To load a template from this environment you just have to call the :meth:`get_template` method which then returns the loaded :class:`Template`:: template = env.get_template('mytemplate.html') To render it with some variables, just call the :meth:`render` method:: print template.render(the='variables', go='here') Using a template loader rather than passing strings to :class:`Template` or :meth:`Environment.from_string` has multiple advantages. Besides being a lot easier to use it also enables template inheritance. .. admonition:: Notes on Autoescaping In future versions of Jinja2 we might enable autoescaping by default for security reasons. As such you are encouraged to explicitly configure autoescaping now instead of relying on the default. Unicode ------- Jinja2 is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters. Additionally newlines are normalized to one end of line sequence which is per default UNIX style (``\n``). Python 2.x supports two ways of representing string objects. One is the `str` type and the other is the `unicode` type, both of which extend a type called `basestring`. Unfortunately the default is `str` which should not be used to store text based information unless only ASCII characters are used. With Python 2.6 it is possible to make `unicode` the default on a per module level and with Python 3 it will be the default. To explicitly use a Unicode string you have to prefix the string literal with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will store the string as Unicode by decoding the string with the character encoding from the current Python module. If no encoding is specified this defaults to 'ASCII' which means that you can't use any non ASCII identifier. To set a better module encoding add the following comment to the first or second line of the Python module using the Unicode literal:: # -*- coding: utf-8 -*- We recommend utf-8 as Encoding for Python modules and templates as it's possible to represent every Unicode character in utf-8 and because it's backwards compatible to ASCII. For Jinja2 the default encoding of templates is assumed to be utf-8. It is not possible to use Jinja2 to process non-Unicode data. The reason for this is that Jinja2 uses Unicode already on the language level. For example Jinja2 treats the non-breaking space as valid whitespace inside expressions which requires knowledge of the encoding or operating on an Unicode string. For more details about Unicode in Python have a look at the excellent `Unicode documentation`_. Another important thing is how Jinja2 is handling string literals in templates. A naive implementation would be using Unicode strings for all string literals but it turned out in the past that this is problematic as some libraries are typechecking against `str` explicitly. For example `datetime.strftime` does not accept Unicode arguments. To not break it completely Jinja2 is returning `str` for strings that fit into ASCII and for everything else `unicode`: >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module >>> m.a 'foo' >>> m.b u'f\xf6\xf6' .. _Unicode documentation: https://docs.python.org/dev/howto/unicode.html High Level API -------------- The high-level API is the API you will use in the application to load and render Jinja2 templates. The :ref:`low-level-api` on the other side is only useful if you want to dig deeper into Jinja2 or :ref:`develop extensions `. .. autoclass:: Environment([options]) :members: from_string, get_template, select_template, get_or_select_template, join_path, extend, compile_expression, compile_templates, list_templates, add_extension .. attribute:: shared If a template was created by using the :class:`Template` constructor an environment is created automatically. These environments are created as shared environments which means that multiple templates may have the same anonymous environment. For all shared environments this attribute is `True`, else `False`. .. attribute:: sandboxed If the environment is sandboxed this attribute is `True`. For the sandbox mode have a look at the documentation for the :class:`~jinja2.sandbox.SandboxedEnvironment`. .. attribute:: filters A dict of filters for this environment. As long as no template was loaded it's safe to add new filters or remove old. For custom filters see :ref:`writing-filters`. For valid filter names have a look at :ref:`identifier-naming`. .. attribute:: tests A dict of test functions for this environment. As long as no template was loaded it's safe to modify this dict. For custom tests see :ref:`writing-tests`. For valid test names have a look at :ref:`identifier-naming`. .. attribute:: globals A dict of global variables. These variables are always available in a template. As long as no template was loaded it's safe to modify this dict. For more details see :ref:`global-namespace`. For valid object names have a look at :ref:`identifier-naming`. .. attribute:: policies A dictionary with :ref:`policies`. These can be reconfigured to change the runtime behavior or certain template features. Usually these are security related. .. attribute:: code_generator_class The class used for code generation. This should not be changed in most cases, unless you need to modify the Python code a template compiles to. .. attribute:: context_class The context used for templates. This should not be changed in most cases, unless you need to modify internals of how template variables are handled. For details, see :class:`~jinja2.runtime.Context`. .. automethod:: overlay([options]) .. method:: undefined([hint, obj, name, exc]) Creates a new :class:`Undefined` object for `name`. This is useful for filters or functions that may return undefined objects for some operations. All parameters except of `hint` should be provided as keyword parameters for better readability. The `hint` is used as error message for the exception if provided, otherwise the error message will be generated from `obj` and `name` automatically. The exception provided as `exc` is raised if something with the generated undefined object is done that the undefined object does not allow. The default exception is :exc:`UndefinedError`. If a `hint` is provided the `name` may be omitted. The most common way to create an undefined object is by providing a name only:: return environment.undefined(name='some_name') This means that the name `some_name` is not defined. If the name was from an attribute of an object it makes sense to tell the undefined object the holder object to improve the error message:: if not hasattr(obj, 'attr'): return environment.undefined(obj=obj, name='attr') For a more complex example you can provide a hint. For example the :func:`first` filter creates an undefined object that way:: return environment.undefined('no first item, sequence was empty') If it the `name` or `obj` is known (for example because an attribute was accessed) it should be passed to the undefined object, even if a custom `hint` is provided. This gives undefined objects the possibility to enhance the error message. .. autoclass:: Template :members: module, make_module .. attribute:: globals The dict with the globals of that template. It's unsafe to modify this dict as it may be shared with other templates or the environment that loaded the template. .. attribute:: name The loading name of the template. If the template was loaded from a string this is `None`. .. attribute:: filename The filename of the template on the file system if it was loaded from there. Otherwise this is `None`. .. automethod:: render([context]) .. automethod:: generate([context]) .. automethod:: stream([context]) .. automethod:: render_async([context]) .. automethod:: generate_async([context]) .. autoclass:: jinja2.environment.TemplateStream() :members: disable_buffering, enable_buffering, dump Autoescaping ------------ .. versionchanged:: 2.4 Jinja2 now comes with autoescaping support. As of Jinja 2.9 the autoescape extension is removed and built-in. However autoescaping is not yet enabled by default though this will most likely change in the future. It's recommended to configure a sensible default for autoescaping. This makes it possible to enable and disable autoescaping on a per-template basis (HTML versus text for instance). .. autofunction:: jinja2.select_autoescape Here a recommended setup that enables autoescaping for templates ending in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default for all other extensions. You can use the :func:`~jinja2.select_autoescape` function for this:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']), loader=PackageLoader('mypackage')) The :func:`~jinja.select_autoescape` function returns a function that works rougly like this:: def autoescape(template_name): if template_name is None: return False if template_name.endswith(('.html', '.htm', '.xml')) When implementing a guessing autoescape function, make sure you also accept `None` as valid template name. This will be passed when generating templates from strings. You should always configure autoescaping as defaults in the future might change. Inside the templates the behaviour can be temporarily changed by using the `autoescape` block (see :ref:`autoescape-overrides`). .. _identifier-naming: Notes on Identifiers -------------------- Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters are currently not allowed. This limitation will probably go away as soon as unicode identifiers are fully specified for Python 3. Filters and tests are looked up in separate namespaces and have slightly modified identifier syntax. Filters and tests may contain dots to group filters and tests by topic. For example it's perfectly valid to add a function into the filter dict and call it `to.unicode`. The regular expression for filter and test identifiers is ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. Undefined Types --------------- These classes can be used as undefined types. The :class:`Environment` constructor takes an `undefined` parameter that can be one of those classes or a custom subclass of :class:`Undefined`. Whenever the template engine is unable to look up a name or access an attribute one of those objects is created and returned. Some operations on undefined values are then allowed, others fail. The closest to regular Python behavior is the `StrictUndefined` which disallows all operations beside testing if it's an undefined object. .. autoclass:: jinja2.Undefined() .. attribute:: _undefined_hint Either `None` or an unicode string with the error message for the undefined object. .. attribute:: _undefined_obj Either `None` or the owner object that caused the undefined object to be created (for example because an attribute does not exist). .. attribute:: _undefined_name The name for the undefined variable / attribute or just `None` if no such information exists. .. attribute:: _undefined_exception The exception that the undefined object wants to raise. This is usually one of :exc:`UndefinedError` or :exc:`SecurityError`. .. method:: _fail_with_undefined_error(\*args, \**kwargs) When called with any arguments this method raises :attr:`_undefined_exception` with an error message generated from the undefined hints stored on the undefined object. .. autoclass:: jinja2.DebugUndefined() .. autoclass:: jinja2.StrictUndefined() There is also a factory function that can decorate undefined objects to implement logging on failures: .. autofunction:: jinja2.make_logging_undefined Undefined objects are created by calling :attr:`undefined`. .. admonition:: Implementation :class:`Undefined` objects are implemented by overriding the special `__underscore__` methods. For example the default :class:`Undefined` class implements `__unicode__` in a way that it returns an empty string, however `__int__` and others still fail with an exception. To allow conversion to int by returning ``0`` you can implement your own:: class NullUndefined(Undefined): def __int__(self): return 0 def __float__(self): return 0.0 To disallow a method, just override it and raise :attr:`~Undefined._undefined_exception`. Because this is a very common idom in undefined objects there is the helper method :meth:`~Undefined._fail_with_undefined_error` that does the error raising automatically. Here a class that works like the regular :class:`Undefined` but chokes on iteration:: class NonIterableUndefined(Undefined): __iter__ = Undefined._fail_with_undefined_error The Context ----------- .. autoclass:: jinja2.runtime.Context() :members: resolve, get_exported, get_all .. attribute:: parent A dict of read only, global variables the template looks up. These can either come from another :class:`Context`, from the :attr:`Environment.globals` or :attr:`Template.globals` or points to a dict created by combining the globals with the variables passed to the render function. It must not be altered. .. attribute:: vars The template local variables. This list contains environment and context functions from the :attr:`parent` scope as well as local modifications and exported variables from the template. The template will modify this dict during template evaluation but filters and context functions are not allowed to modify it. .. attribute:: environment The environment that loaded the template. .. attribute:: exported_vars This set contains all the names the template exports. The values for the names are in the :attr:`vars` dict. In order to get a copy of the exported variables as dict, :meth:`get_exported` can be used. .. attribute:: name The load name of the template owning this context. .. attribute:: blocks A dict with the current mapping of blocks in the template. The keys in this dict are the names of the blocks, and the values a list of blocks registered. The last item in each list is the current active block (latest in the inheritance chain). .. attribute:: eval_ctx The current :ref:`eval-context`. .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs) .. admonition:: Implementation Context is immutable for the same reason Python's frame locals are immutable inside functions. Both Jinja2 and Python are not using the context / frame locals as data storage for variables but only as primary data source. When a template accesses a variable the template does not define, Jinja2 looks up the variable in the context, after that the variable is treated as if it was defined in the template. .. _loaders: Loaders ------- Loaders are responsible for loading templates from a resource such as the file system. The environment will keep the compiled modules in memory like Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in size by default and templates are automatically reloaded. All loaders are subclasses of :class:`BaseLoader`. If you want to create your own loader, subclass :class:`BaseLoader` and override `get_source`. .. autoclass:: jinja2.BaseLoader :members: get_source, load Here a list of the builtin loaders Jinja2 provides: .. autoclass:: jinja2.FileSystemLoader .. autoclass:: jinja2.PackageLoader .. autoclass:: jinja2.DictLoader .. autoclass:: jinja2.FunctionLoader .. autoclass:: jinja2.PrefixLoader .. autoclass:: jinja2.ChoiceLoader .. autoclass:: jinja2.ModuleLoader .. _bytecode-cache: Bytecode Cache -------------- Jinja 2.1 and higher support external bytecode caching. Bytecode caches make it possible to store the generated bytecode on the file system or a different location to avoid parsing the templates on first use. This is especially useful if you have a web application that is initialized on the first request and Jinja compiles many templates at once which slows down the application. To use a bytecode cache, instantiate it and pass it to the :class:`Environment`. .. autoclass:: jinja2.BytecodeCache :members: load_bytecode, dump_bytecode, clear .. autoclass:: jinja2.bccache.Bucket :members: write_bytecode, load_bytecode, bytecode_from_string, bytecode_to_string, reset .. attribute:: environment The :class:`Environment` that created the bucket. .. attribute:: key The unique cache key for this bucket .. attribute:: code The bytecode if it's loaded, otherwise `None`. Builtin bytecode caches: .. autoclass:: jinja2.FileSystemBytecodeCache .. autoclass:: jinja2.MemcachedBytecodeCache Async Support ------------- Starting with version 2.9, Jinja2 also supports the Python `async` and `await` constructs. As far as template designers go this feature is entirely opaque to them however as a developer you should be aware of how it's implemented as it influences what type of APIs you can safely expose to the template environment. First you need to be aware that by default async support is disabled as enabling it will generate different template code behind the scenes which passes everything through the asyncio event loop. This is important to understand because it has some impact to what you are doing: * template rendering will require an event loop to be set for the current thread (``asyncio.get_event_loop`` needs to return one) * all template generation code internally runs async generators which means that you will pay a performance penalty even if the non sync methods are used! * The sync methods are based on async methods if the async mode is enabled which means that `render` for instance will internally invoke `render_async` and run it as part of the current event loop until the execution finished. Awaitable objects can be returned from functions in templates and any function call in a template will automatically await the result. This means that you can let provide a method that asynchronously loads data from a database if you so desire and from the template designer's point of view this is just another function they can call. This means that the ``await`` you would normally issue in Python is implied. However this only applies to function calls. If an attribute for instance would be an avaitable object then this would not result in the expected behavior. Likewise iterations with a `for` loop support async iterators. .. _policies: Policies -------- Starting with Jinja 2.9 policies can be configured on the environment which can slightly influence how filters and other template constructs behave. They can be configured with the :attr:`~jinja2.Environment.policies` attribute. Example:: env.policies['urlize.rel'] = 'nofollow noopener' ``compiler.ascii_str``: This boolean controls on Python 2 if Jinja2 should store ASCII only literals as bytestring instead of unicode strings. This used to be always enabled for Jinja versions below 2.9 and now can be changed. Traditionally it was done this way since some APIs in Python 2 failed badly for unicode strings (for instance the datetime strftime API). Now however sometimes the inverse is true (for instance str.format). If this is set to False then all strings are stored as unicode internally. ``truncate.leeway``: Configures the leeway default for the `truncate` filter. Leeway as introduced in 2.9 but to restore compatibility with older templates it can be configured to `0` to get the old behavior back. The default is `5`. ``urlize.rel``: A string that defines the items for the `rel` attribute of generated links with the `urlize` filter. These items are always added. The default is `noopener`. ``urlize.target``: The default target that is issued for links from the `urlize` filter if no other target is defined by the call explicitly. ``json.dumps_function``: If this is set to a value other than `None` then the `tojson` filter will dump with this function instead of the default one. Note that this function should accept arbitrary extra arguments which might be passed in the future from the filter. Currently the only argument that might be passed is `indent`. The default dump function is ``json.dumps``. ``json.dumps_kwargs``: Keyword arguments to be passed to the dump function. The default is ``{'sort_keys': True}``. .. _ext-i18n-trimmed: ``ext.i18n.trimmed``: If this is set to `True`, ``{% trans %}`` blocks of the :ref:`i18n-extension` will always unify linebreaks and surrounding whitespace as if the `trimmed` modifier was used. Utilities --------- These helper functions and classes are useful if you add custom filters or functions to a Jinja2 environment. .. autofunction:: jinja2.environmentfilter .. autofunction:: jinja2.contextfilter .. autofunction:: jinja2.evalcontextfilter .. autofunction:: jinja2.environmentfunction .. autofunction:: jinja2.contextfunction .. autofunction:: jinja2.evalcontextfunction .. function:: escape(s) Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s` to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. This function will not escaped objects that do have an HTML representation such as already escaped data. The return value is a :class:`Markup` string. .. autofunction:: jinja2.clear_caches .. autofunction:: jinja2.is_undefined .. autoclass:: jinja2.Markup([string]) :members: escape, unescape, striptags .. admonition:: Note The Jinja2 :class:`Markup` class is compatible with at least Pylons and Genshi. It's expected that more template engines and framework will pick up the `__html__` concept soon. Exceptions ---------- .. autoexception:: jinja2.TemplateError .. autoexception:: jinja2.UndefinedError .. autoexception:: jinja2.TemplateNotFound .. autoexception:: jinja2.TemplatesNotFound .. autoexception:: jinja2.TemplateSyntaxError .. attribute:: message The error message as utf-8 bytestring. .. attribute:: lineno The line number where the error occurred .. attribute:: name The load name for the template as unicode string. .. attribute:: filename The filename that loaded the template as bytestring in the encoding of the file system (most likely utf-8 or mbcs on Windows systems). The reason why the filename and error message are bytestrings and not unicode strings is that Python 2.x is not using unicode for exceptions and tracebacks as well as the compiler. This will change with Python 3. .. autoexception:: jinja2.TemplateRuntimeError .. autoexception:: jinja2.TemplateAssertionError .. _writing-filters: Custom Filters -------------- Custom filters are just regular Python functions that take the left side of the filter as first argument and the arguments passed to the filter as extra arguments or keyword arguments. For example in the filter ``{{ 42|myfilter(23) }}`` the function would be called with ``myfilter(42, 23)``. Here for example a simple filter that can be applied to datetime objects to format them:: def datetimeformat(value, format='%H:%M / %d-%m-%Y'): return value.strftime(format) You can register it on the template environment by updating the :attr:`~Environment.filters` dict on the environment:: environment.filters['datetimeformat'] = datetimeformat Inside the template it can then be used as follows: .. sourcecode:: jinja written on: {{ article.pub_date|datetimeformat }} publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} Filters can also be passed the current template context or environment. This is useful if a filter wants to return an undefined value or check the current :attr:`~Environment.autoescape` setting. For this purpose three decorators exist: :func:`environmentfilter`, :func:`contextfilter` and :func:`evalcontextfilter`. Here a small example filter that breaks a text into HTML line breaks and paragraphs and marks the return value as safe HTML string if autoescaping is enabled:: import re from jinja2 import evalcontextfilter, Markup, escape _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') @evalcontextfilter def nl2br(eval_ctx, value): result = u'\n\n'.join(u'

    %s

    ' % p.replace('\n', Markup('
    \n')) for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result Context filters work the same just that the first argument is the current active :class:`Context` rather than the environment. .. _eval-context: Evaluation Context ------------------ The evaluation context (short eval context or eval ctx) is a new object introduced in Jinja 2.4 that makes it possible to activate and deactivate compiled features at runtime. Currently it is only used to enable and disable the automatic escaping but can be used for extensions as well. In previous Jinja versions filters and functions were marked as environment callables in order to check for the autoescape status from the environment. In new versions it's encouraged to check the setting from the evaluation context instead. Previous versions:: @environmentfilter def filter(env, value): result = do_something(value) if env.autoescape: result = Markup(result) return result In new versions you can either use a :func:`contextfilter` and access the evaluation context from the actual context, or use a :func:`evalcontextfilter` which directly passes the evaluation context to the function:: @contextfilter def filter(context, value): result = do_something(value) if context.eval_ctx.autoescape: result = Markup(result) return result @evalcontextfilter def filter(eval_ctx, value): result = do_something(value) if eval_ctx.autoescape: result = Markup(result) return result The evaluation context must not be modified at runtime. Modifications must only happen with a :class:`nodes.EvalContextModifier` and :class:`nodes.ScopedEvalContextModifier` from an extension, not on the eval context object itself. .. autoclass:: jinja2.nodes.EvalContext .. attribute:: autoescape `True` or `False` depending on if autoescaping is active or not. .. attribute:: volatile `True` if the compiler cannot evaluate some expressions at compile time. At runtime this should always be `False`. .. _writing-tests: Custom Tests ------------ Tests work like filters just that there is no way for a test to get access to the environment or context and that they can't be chained. The return value of a test should be `True` or `False`. The purpose of a test is to give the template designers the possibility to perform type and conformability checks. Here a simple test that checks if a variable is a prime number:: import math def is_prime(n): if n == 2: return True for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True You can register it on the template environment by updating the :attr:`~Environment.tests` dict on the environment:: environment.tests['prime'] = is_prime A template designer can then use the test like this: .. sourcecode:: jinja {% if 42 is prime %} 42 is a prime number {% else %} 42 is not a prime number {% endif %} .. _global-namespace: The Global Namespace -------------------- Variables stored in the :attr:`Environment.globals` dict are special as they are available for imported templates too, even if they are imported without context. This is the place where you can put variables and functions that should be available all the time. Additionally :attr:`Template.globals` exist that are variables available to a specific template that are available to all :meth:`~Template.render` calls. .. _low-level-api: Low Level API ------------- The low level API exposes functionality that can be useful to understand some implementation details, debugging purposes or advanced :ref:`extension ` techniques. Unless you know exactly what you are doing we don't recommend using any of those. .. automethod:: Environment.lex .. automethod:: Environment.parse .. automethod:: Environment.preprocess .. automethod:: Template.new_context .. method:: Template.root_render_func(context) This is the low level render function. It's passed a :class:`Context` that has to be created by :meth:`new_context` of the same template or a compatible template. This render function is generated by the compiler from the template code and returns a generator that yields unicode strings. If an exception in the template code happens the template engine will not rewrite the exception but pass through the original one. As a matter of fact this function should only be called from within a :meth:`render` / :meth:`generate` / :meth:`stream` call. .. attribute:: Template.blocks A dict of block render functions. Each of these functions works exactly like the :meth:`root_render_func` with the same limitations. .. attribute:: Template.is_up_to_date This attribute is `False` if there is a newer version of the template available, otherwise `True`. .. admonition:: Note The low-level API is fragile. Future Jinja2 versions will try not to change it in a backwards incompatible way but modifications in the Jinja2 core may shine through. For example if Jinja2 introduces a new AST node in later versions that may be returned by :meth:`~Environment.parse`. The Meta API ------------ .. versionadded:: 2.2 The meta API returns some information about abstract syntax trees that could help applications to implement more advanced template concepts. All the functions of the meta API operate on an abstract syntax tree as returned by the :meth:`Environment.parse` method. .. autofunction:: jinja2.meta.find_undeclared_variables .. autofunction:: jinja2.meta.find_referenced_templates PKê|>]‡øÐ.00html/_sources/changelog.rst.txtnu„[µü¤.. module:: jinja2 .. include:: ../CHANGES.rst PKê|>]yL9æ+æ+ html/_sources/extensions.rst.txtnu„[µü¤.. _jinja-extensions: Extensions ========== Jinja2 supports extensions that can add extra filters, tests, globals or even extend the parser. The main motivation of extensions is to move often used code into a reusable class like adding support for internationalization. Adding Extensions ----------------- Extensions are added to the Jinja2 environment at creation time. Once the environment is created additional extensions cannot be added. To add an extension pass a list of extension classes or import paths to the `extensions` parameter of the :class:`Environment` constructor. The following example creates a Jinja2 environment with the i18n extension loaded:: jinja_env = Environment(extensions=['jinja2.ext.i18n']) .. _i18n-extension: i18n Extension -------------- **Import name:** `jinja2.ext.i18n` The i18n extension can be used in combination with `gettext`_ or `babel`_. If the i18n extension is enabled Jinja2 provides a `trans` statement that marks the wrapped string as translatable and calls `gettext`. After enabling, dummy `_` function that forwards calls to `gettext` is added to the environment globals. An internationalized application then has to provide a `gettext` function and optionally an `ngettext` function into the namespace, either globally or for each rendering. Environment Methods ~~~~~~~~~~~~~~~~~~~ After enabling the extension, the environment provides the following additional methods: .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False) Installs a translation globally for that environment. The translations object provided must implement at least `ugettext` and `ungettext`. The `gettext.NullTranslations` and `gettext.GNUTranslations` classes as well as `Babel`_\s `Translations` class are supported. .. versionchanged:: 2.5 newstyle gettext added .. method:: jinja2.Environment.install_null_translations(newstyle=False) Install dummy gettext functions. This is useful if you want to prepare the application for internationalization but don't want to implement the full internationalization system yet. .. versionchanged:: 2.5 newstyle gettext added .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False) Installs the given `gettext` and `ngettext` callables into the environment as globals. They are supposed to behave exactly like the standard library's :func:`gettext.ugettext` and :func:`gettext.ungettext` functions. If `newstyle` is activated, the callables are wrapped to work like newstyle callables. See :ref:`newstyle-gettext` for more information. .. versionadded:: 2.5 .. method:: jinja2.Environment.uninstall_gettext_translations() Uninstall the translations again. .. method:: jinja2.Environment.extract_translations(source) Extract localizable strings from the given template node or source. For every string found this function yields a ``(lineno, function, message)`` tuple, where: * `lineno` is the number of the line on which the string was found, * `function` is the name of the `gettext` function used (if the string was extracted from embedded Python code), and * `message` is the string itself (a `unicode` object, or a tuple of `unicode` objects for functions with multiple string arguments). If `Babel`_ is installed, :ref:`the babel integration ` can be used to extract strings for babel. For a web application that is available in multiple languages but gives all the users the same language (for example a multilingual forum software installed for a French community) may load the translations once and add the translation methods to the environment at environment generation time:: translations = get_gettext_translations() env = Environment(extensions=['jinja2.ext.i18n']) env.install_gettext_translations(translations) The `get_gettext_translations` function would return the translator for the current configuration. (For example by using `gettext.find`) The usage of the `i18n` extension for template designers is covered as part :ref:`of the template documentation `. .. _gettext: https://docs.python.org/dev/library/gettext .. _Babel: http://babel.pocoo.org/ .. _newstyle-gettext: Whitespace Trimming ~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2.10 Linebreaks and surrounding whitespace can be automatically trimmed by enabling the ``ext.i18n.trimmed`` :ref:`policy `. Newstyle Gettext ~~~~~~~~~~~~~~~~ .. versionadded:: 2.5 Starting with version 2.5 you can use newstyle gettext calls. These are inspired by trac's internal gettext functions and are fully supported by the babel extraction tool. They might not work as expected by other extraction tools in case you are not using Babel's. What's the big difference between standard and newstyle gettext calls? In general they are less to type and less error prone. Also if they are used in an autoescaping environment they better support automatic escaping. Here are some common differences between old and new calls: standard gettext: .. sourcecode:: html+jinja {{ gettext('Hello World!') }} {{ gettext('Hello %(name)s!')|format(name='World') }} {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format( num=apples|count )}} newstyle gettext looks like this instead: .. sourcecode:: html+jinja {{ gettext('Hello World!') }} {{ gettext('Hello %(name)s!', name='World') }} {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} The advantages of newstyle gettext are that you have less to type and that named placeholders become mandatory. The latter sounds like a disadvantage but solves a lot of troubles translators are often facing when they are unable to switch the positions of two placeholder. With newstyle gettext, all format strings look the same. Furthermore with newstyle gettext, string formatting is also used if no placeholders are used which makes all strings behave exactly the same. Last but not least are newstyle gettext calls able to properly mark strings for autoescaping which solves lots of escaping related issues many templates are experiencing over time when using autoescaping. Expression Statement -------------------- **Import name:** `jinja2.ext.do` The "do" aka expression-statement extension adds a simple `do` tag to the template engine that works like a variable expression but ignores the return value. .. _loopcontrols-extension: Loop Controls ------------- **Import name:** `jinja2.ext.loopcontrols` This extension adds support for `break` and `continue` in loops. After enabling, Jinja2 provides those two keywords which work exactly like in Python. .. _with-extension: With Statement -------------- **Import name:** `jinja2.ext.with_` .. versionchanged:: 2.9 This extension is now built-in and no longer does anything. .. _autoescape-extension: Autoescape Extension -------------------- **Import name:** `jinja2.ext.autoescape` .. versionchanged:: 2.9 This extension was removed and is now built-in. Enabling the extension no longer does anything. .. _writing-extensions: Writing Extensions ------------------ .. module:: jinja2.ext By writing extensions you can add custom tags to Jinja2. This is a non-trivial task and usually not needed as the default tags and expressions cover all common use cases. The i18n extension is a good example of why extensions are useful. Another one would be fragment caching. When writing extensions you have to keep in mind that you are working with the Jinja2 template compiler which does not validate the node tree you are passing to it. If the AST is malformed you will get all kinds of compiler or runtime errors that are horrible to debug. Always make sure you are using the nodes you create correctly. The API documentation below shows which nodes exist and how to use them. Example Extension ~~~~~~~~~~~~~~~~~ The following example implements a `cache` tag for Jinja2 by using the `Werkzeug`_ caching contrib module: .. literalinclude:: cache_extension.py :language: python And here is how you use it in an environment:: from jinja2 import Environment from werkzeug.contrib.cache import SimpleCache env = Environment(extensions=[FragmentCacheExtension]) env.fragment_cache = SimpleCache() Inside the template it's then possible to mark blocks as cacheable. The following example caches a sidebar for 300 seconds: .. sourcecode:: html+jinja {% cache 'sidebar', 300 %} {% endcache %} .. _Werkzeug: http://werkzeug.pocoo.org/ Extension API ~~~~~~~~~~~~~ Extensions always have to extend the :class:`jinja2.ext.Extension` class: .. autoclass:: Extension :members: preprocess, filter_stream, parse, attr, call_method .. attribute:: identifier The identifier of the extension. This is always the true import name of the extension class and must not be changed. .. attribute:: tags If the extension implements custom tags this is a set of tag names the extension is listening for. Parser API ~~~~~~~~~~ The parser passed to :meth:`Extension.parse` provides ways to parse expressions of different types. The following methods may be used by extensions: .. autoclass:: jinja2.parser.Parser :members: parse_expression, parse_tuple, parse_assign_target, parse_statements, free_identifier, fail .. attribute:: filename The filename of the template the parser processes. This is **not** the load name of the template. For the load name see :attr:`name`. For templates that were not loaded form the file system this is `None`. .. attribute:: name The load name of the template. .. attribute:: stream The current :class:`~jinja2.lexer.TokenStream` .. autoclass:: jinja2.lexer.TokenStream :members: push, look, eos, skip, __next__, next_if, skip_if, expect .. attribute:: current The current :class:`~jinja2.lexer.Token`. .. autoclass:: jinja2.lexer.Token :members: test, test_any .. attribute:: lineno The line number of the token .. attribute:: type The type of the token. This string is interned so you may compare it with arbitrary strings using the `is` operator. .. attribute:: value The value of the token. There is also a utility function in the lexer module that can count newline characters in strings: .. autofunction:: jinja2.lexer.count_newlines AST ~~~ The AST (Abstract Syntax Tree) is used to represent a template after parsing. It's build of nodes that the compiler then converts into executable Python code objects. Extensions that provide custom statements can return nodes to execute custom Python code. The list below describes all nodes that are currently available. The AST may change between Jinja2 versions but will stay backwards compatible. For more information have a look at the repr of :meth:`jinja2.Environment.parse`. .. module:: jinja2.nodes .. jinjanodes:: .. autoexception:: Impossible PKê|>]JÊ z··html/_sources/faq.rst.txtnu„[µü¤Frequently Asked Questions ========================== This page answers some of the often asked questions about Jinja. .. highlight:: html+jinja Why is it called Jinja? ----------------------- The name Jinja was chosen because it's the name of a Japanese temple and temple and template share a similar pronunciation. It is not named after the city in Uganda. How fast is it? --------------- We really hate benchmarks especially since they don't reflect much. The performance of a template depends on many factors and you would have to benchmark different engines in different situations. The benchmarks from the testsuite show that Jinja2 has a similar performance to `Mako`_ and is between 10 and 20 times faster than Django's template engine or Genshi. These numbers should be taken with tons of salt as the benchmarks that took these numbers only test a few performance related situations such as looping. Generally speaking the performance of a template engine doesn't matter much as the usual bottleneck in a web application is either the database or the application code. .. _Mako: http://www.makotemplates.org/ How Compatible is Jinja2 with Django? ------------------------------------- The default syntax of Jinja2 matches Django syntax in many ways. However this similarity doesn't mean that you can use a Django template unmodified in Jinja2. For example filter arguments use a function call syntax rather than a colon to separate filter name and arguments. Additionally the extension interface in Jinja is fundamentally different from the Django one which means that your custom tags won't work any longer. Generally speaking you will use much less custom extensions as the Jinja template system allows you to use a certain subset of Python expressions which can replace most Django extensions. For example instead of using something like this:: {% load comments %} {% get_latest_comments 10 as latest_comments %} {% for comment in latest_comments %} ... {% endfor %} You will most likely provide an object with attributes to retrieve comments from the database:: {% for comment in models.comments.latest(10) %} ... {% endfor %} Or directly provide the model for quick testing:: {% for comment in Comment.objects.order_by('-pub_date')[:10] %} ... {% endfor %} Please keep in mind that even though you may put such things into templates it still isn't a good idea. Queries should go into the view code and not the template! Isn't it a terrible idea to put Logic into Templates? ----------------------------------------------------- Without a doubt you should try to remove as much logic from templates as possible. But templates without any logic mean that you have to do all the processing in the code which is boring and stupid. A template engine that does that is shipped with Python and called `string.Template`. Comes without loops and if conditions and is by far the fastest template engine you can get for Python. So some amount of logic is required in templates to keep everyone happy. And Jinja leaves it pretty much to you how much logic you want to put into templates. There are some restrictions in what you can do and what not. Jinja2 neither allows you to put arbitrary Python code into templates nor does it allow all Python expressions. The operators are limited to the most common ones and more advanced expressions such as list comprehensions and generator expressions are not supported. This keeps the template engine easier to maintain and templates more readable. Why is Autoescaping not the Default? ------------------------------------ There are multiple reasons why automatic escaping is not the default mode and also not the recommended one. While automatic escaping of variables means that you will less likely have an XSS problem it also causes a huge amount of extra processing in the template engine which can cause serious performance problems. As Python doesn't provide a way to mark strings as unsafe Jinja has to hack around that limitation by providing a custom string class (the :class:`Markup` string) that safely interacts with safe and unsafe strings. With explicit escaping however the template engine doesn't have to perform any safety checks on variables. Also a human knows not to escape integers or strings that may never contain characters one has to escape or already HTML markup. For example when iterating over a list over a table of integers and floats for a table of statistics the template designer can omit the escaping because he knows that integers or floats don't contain any unsafe parameters. Additionally Jinja2 is a general purpose template engine and not only used for HTML/XML generation. For example you may generate LaTeX, emails, CSS, JavaScript, or configuration files. Why is the Context immutable? ----------------------------- When writing a :func:`contextfunction` or something similar you may have noticed that the context tries to stop you from modifying it. If you have managed to modify the context by using an internal context API you may have noticed that changes in the context don't seem to be visible in the template. The reason for this is that Jinja uses the context only as primary data source for template variables for performance reasons. If you want to modify the context write a function that returns a variable instead that one can assign to a variable by using set:: {% set comments = get_latest_comments() %} My tracebacks look weird. What's happening? -------------------------------------------- If the debugsupport module is not compiled and you are using a Python installation without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine) Jinja2 is unable to provide correct debugging information and the traceback may be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and it's not possible to use the debugsupport extension. If you are working in the Google AppEngine development server you can whitelist the ctypes module to restore the tracebacks. This however won't work in production environments:: import os if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): from google.appengine.tools.devappserver2.python import sandbox sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] Credit for this snippet goes to `Thomas Johansson `_ Why is there no Python 2.3/2.4/2.5/3.1/3.2 support? --------------------------------------------------- Python 2.3 is missing a lot of features that are used heavily in Jinja2. This decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes harder to maintain the code for older Python versions. If you really need Python 2.3 support you either have to use `Jinja 1`_ or other templating engines that still support 2.3. Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting Python 2 and 3 by the same sourcecode (without using 2to3). It was required to drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode literals in a way compatible to each other version. If you really need support for older Python 2 (or 3) versions, you can just use Jinja2 2.6. My Macros are overridden by something ------------------------------------- In some situations the Jinja scoping appears arbitrary: layout.tmpl: .. sourcecode:: jinja {% macro foo() %}LAYOUT{% endmacro %} {% block body %}{% endblock %} child.tmpl: .. sourcecode:: jinja {% extends 'layout.tmpl' %} {% macro foo() %}CHILD{% endmacro %} {% block body %}{{ foo() }}{% endblock %} This will print ``LAYOUT`` in Jinja2. This is a side effect of having the parent template evaluated after the child one. This allows child templates passing information to the parent template. To avoid this issue rename the macro or variable in the parent template to have an uncommon prefix. .. _Jinja 1: http://jinja.pocoo.org/1/ PKê|>])ˆõ™ããhtml/_sources/index.rst.txtnu„[µü¤Welcome to Jinja2 ================= Jinja2 is a modern and designer-friendly templating language for Python, modelled after Django's templates. It is fast, widely used and secure with the optional sandboxed template execution environment: .. sourcecode:: html+jinja {% block title %}{% endblock %} **Features:** - sandboxed execution - powerful automatic HTML escaping system for XSS prevention - template inheritance - compiles down to the optimal python code just in time - optional ahead-of-time template compilation - easy to debug. Line numbers of exceptions directly point to the correct line in the template. - configurable syntax .. include:: contents.rst.inc If you can't find the information you're looking for, have a look at the index or try to find it using the search function: * :ref:`genindex` * :ref:`search` PKê|>]×´Œ í í !html/_sources/integration.rst.txtnu„[µü¤Integration =========== Jinja2 provides some code for integration into other tools such as frameworks, the `Babel`_ library or your favourite editor for fancy code highlighting. This is a brief description of whats included. Files to help integration are available `here. `_ .. _babel-integration: Babel Integration ----------------- Jinja provides support for extracting gettext messages from templates via a `Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel support is implemented as part of the :ref:`i18n-extension` extension. Gettext messages extracted from both `trans` tags and code expressions. To extract gettext messages from templates, the project needs a Jinja2 section in its Babel extraction method `mapping file`_: .. sourcecode:: ini [jinja2: **/templates/**.html] encoding = utf-8 The syntax related options of the :class:`Environment` are also available as configuration values in the mapping file. For example to tell the extraction that templates use ``%`` as `line_statement_prefix` you can use this code: .. sourcecode:: ini [jinja2: **/templates/**.html] encoding = utf-8 line_statement_prefix = % :ref:`jinja-extensions` may also be defined by passing a comma separated list of import paths as `extensions` value. The i18n extension is added automatically. .. versionchanged:: 2.7 Until 2.7 template syntax errors were always ignored. This was done since many people are dropping non template html files into the templates folder and it would randomly fail. The assumption was that testsuites will catch syntax errors in templates anyways. If you don't want that behavior you can add ``silent=false`` to the settings and exceptions are propagated. .. _mapping file: http://babel.pocoo.org/en/latest/messages.html#extraction-method-mapping-and-configuration Pylons ------ With `Pylons`_ 0.9.7 onwards it's incredible easy to integrate Jinja into a Pylons powered application. The template engine is configured in `config/environment.py`. The configuration for Jinja2 looks something like that:: from jinja2 import Environment, PackageLoader config['pylons.app_globals'].jinja_env = Environment( loader=PackageLoader('yourapplication', 'templates') ) After that you can render Jinja templates by using the `render_jinja` function from the `pylons.templating` module. Additionally it's a good idea to set the Pylons' `c` object into strict mode. Per default any attribute to not existing attributes on the `c` object return an empty string and not an undefined object. To change this just use this snippet and add it into your `config/environment.py`:: config['pylons.strict_c'] = True .. _Pylons: http://www.pylonshq.com/ TextMate -------- There is a `bundle for TextMate`_ that supports syntax highlighting for Jinja1 and Jinja2 for text based templates as well as HTML. It also contains a few often used snippets. .. _bundle for TextMate: https://github.com/mitsuhiko/jinja2-tmbundle Vim --- A syntax plugin for `Vim`_ exists in the Vim-scripts directory as well as the `ext` folder at the root of the Jinja2 project. `The script `_ supports Jinja1 and Jinja2. Once installed two file types are available `jinja` and `htmljinja`. The first one for text based templates, the latter for HTML templates. Copy the files into your `syntax` folder. .. _Babel: http://babel.pocoo.org/ .. _Vim: http://www.vim.org/ PKê|>]z½z>>html/_sources/intro.rst.txtnu„[µü¤Introduction ============ This is the documentation for the Jinja2 general purpose templating language. Jinja2 is a library for Python that is designed to be flexible, fast and secure. If you have any exposure to other text-based template languages, such as Smarty or Django, you should feel right at home with Jinja2. It's both designer and developer friendly by sticking to Python's principles and adding functionality useful for templating environments. Prerequisites ------------- Jinja2 works with Python 2.6.x, 2.7.x and >= 3.3. If you are using Python 3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.2 was dropped in Jinja2 version 2.7. If you wish to use the :class:`~jinja2.PackageLoader` class, you will also need `setuptools`_ or `distribute`_ installed at runtime. Installation ------------ You have multiple ways to install Jinja2. If you are unsure what to do, go with the Python egg or tarball. As a Python egg (via `easy_install`) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can install the most recent Jinja2 version using `easy_install`_ or `pip`_:: easy_install Jinja2 pip install Jinja2 This will install a Jinja2 egg in your Python installation's site-packages directory. From the tarball release ~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Download the most recent tarball from the `download page`_ 2. Unpack the tarball 3. ``python setup.py install`` Note that you either have to have `setuptools` or `distribute` installed; the latter is preferred. This will install Jinja2 into your Python installation's site-packages directory. Installing the development version ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Install `git`_ 2. ``git clone git://github.com/pallets/jinja.git`` 3. ``cd jinja2`` 4. ``ln -s jinja2 /usr/lib/python2.X/site-packages`` As an alternative to steps 4 you can also do ``python setup.py develop`` which will install the package via `distribute` in development mode. This also has the advantage that the C extensions are compiled. .. _download page: https://pypi.python.org/pypi/Jinja2 .. _distribute: https://pypi.python.org/pypi/distribute .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall .. _pip: https://pypi.python.org/pypi/pip .. _git: https://git-scm.org/ MarkupSafe Dependency ~~~~~~~~~~~~~~~~~~~~~ As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you install Jinja2 via `pip` or `easy_install` it will be installed automatically for you. .. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe Basic API Usage --------------- This section gives you a brief introduction to the Python API for Jinja2 templates. The most basic way to create a template and render it is through :class:`~jinja2.Template`. This however is not the recommended way to work with it if your templates are not loaded from strings but the file system or another data source: >>> from jinja2 import Template >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') u'Hello John Doe!' By creating an instance of :class:`~jinja2.Template` you get back a new template object that provides a method called :meth:`~jinja2.Template.render` which when called with a dict or keyword arguments expands the template. The dict or keywords arguments passed to the template are the so-called "context" of the template. What you can see here is that Jinja2 is using unicode internally and the return value is an unicode string. So make sure that your application is indeed using unicode internally. Experimental Python 3 Support ----------------------------- Jinja 2.7 brings experimental support for Python >=3.3. It means that all unittests pass on the new version, but there might still be small bugs in there and behavior might be inconsistent. If you notice any bugs, please provide feedback in the `Jinja bug tracker`_. Also please keep in mind that the documentation is written with Python 2 in mind, so you will have to adapt the shown code examples to Python 3 syntax for yourself. .. _Jinja bug tracker: https://github.com/pallets/jinja/issues PKê|>]§?@YSS html/_sources/latexindex.rst.txtnu„[µü¤:orphan: Jinja2 Documentation ==================== .. include:: contents.rst.inc PKê|>]9’Ú!html/_sources/nativetypes.rst.txtnu„[µü¤.. module:: jinja2.nativetypes .. _nativetypes: Native Python Types =================== The default :class:`~jinja2.Environment` renders templates to strings. With :class:`NativeEnvironment`, rendering a template produces a native Python type. This is useful if you are using Jinja outside the context of creating text files. For example, your code may have an intermediate step where users may use templates to define values that will then be passed to a traditional string environment. Examples -------- Adding two values results in an integer, not a string with a number: >>> env = NativeEnvironment() >>> t = env.from_string('{{ x + y }}') >>> result = t.render(x=4, y=2) >>> print(result) 6 >>> print(type(result)) int Rendering list syntax produces a list: >>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]') >>> result = t.render(data=range(5)) >>> print(result) [1, 2, 3, 4, 5] >>> print(type(result)) list Rendering something that doesn't look like a Python literal produces a string: >>> t = env.from_string('{{ x }} * {{ y }}') >>> result = t.render(x=4, y=2) >>> print(result) 4 * 2 >>> print(type(result)) str Rendering a Python object produces that object as long as it is the only node: >>> class Foo: ... def __init__(self, value): ... self.value = value ... >>> result = env.from_string('{{ x }}').render(x=Foo(15)) >>> print(type(result).__name__) Foo >>> print(result.value) 15 API --- .. autoclass:: NativeEnvironment([options]) .. autoclass:: NativeTemplate([options]) :members: render PKê|>]M`™Ð Ð html/_sources/sandbox.rst.txtnu„[µü¤Sandbox ======= The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited. Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration the following piece of code shows how it works: >>> env.from_string("{{ func.func_code }}").render(func=lambda:None) u'' >>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None) Traceback (most recent call last): ... SecurityError: access to attribute 'func_code' of 'function' object is unsafe. API --- .. module:: jinja2.sandbox .. autoclass:: SandboxedEnvironment([options]) :members: is_safe_attribute, is_safe_callable, default_binop_table, default_unop_table, intercepted_binops, intercepted_unops, call_binop, call_unop .. autoclass:: ImmutableSandboxedEnvironment([options]) .. autoexception:: SecurityError .. autofunction:: unsafe .. autofunction:: is_internal_attribute .. autofunction:: modifies_known_mutable .. admonition:: Note The Jinja2 sandbox alone is no solution for perfect security. Especially for web applications you have to keep in mind that users may create templates with arbitrary HTML in so it's crucial to ensure that (if you are running multiple users on the same server) they can't harm each other via JavaScript insertions and much more. Also the sandbox is only as good as the configuration. We strongly recommend only passing non-shared resources to the template and use some sort of whitelisting for attributes. Also keep in mind that templates may raise runtime or compile time errors, so make sure to catch them. Operator Intercepting --------------------- .. versionadded:: 2.6 For maximum performance Jinja2 will let operators call directly the type specific callback methods. This means that it's not possible to have this intercepted by overriding :meth:`Environment.call`. Furthermore a conversion from operator to special method is not always directly possible due to how operators work. For instance for divisions more than one special method exist. With Jinja 2.6 there is now support for explicit operator intercepting. This can be used to customize specific operators as necessary. In order to intercept an operator one has to override the :attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the operator that needs to be intercepted is added to that set Jinja2 will generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop` function. For unary operators the `unary` attributes and methods have to be used instead. The default implementation of :attr:`SandboxedEnvironment.call_binop` will use the :attr:`SandboxedEnvironment.binop_table` to translate operator symbols into callbacks performing the default operator behavior. This example shows how the power (``**``) operator can be disabled in Jinja2:: from jinja2.sandbox import SandboxedEnvironment class MyEnvironment(SandboxedEnvironment): intercepted_binops = frozenset(['**']) def call_binop(self, context, operator, left, right): if operator == '**': return self.undefined('the power operator is unavailable') return SandboxedEnvironment.call_binop(self, context, operator, left, right) Make sure to always call into the super method, even if you are not intercepting the call. Jinja2 might internally call the method to evaluate expressions. PKê|>]DgXm››html/_sources/switching.rst.txtnu„[µü¤Switching from other Template Engines ===================================== .. highlight:: html+jinja If you have used a different template engine in the past and want to switch to Jinja2 here is a small guide that shows the basic syntactic and semantic changes between some common, similar text template engines for Python. Jinja1 ------ Jinja2 is mostly compatible with Jinja1 in terms of API usage and template syntax. The differences between Jinja1 and 2 are explained in the following list. API ~~~ Loaders Jinja2 uses a different loader API. Because the internal representation of templates changed there is no longer support for external caching systems such as memcached. The memory consumed by templates is comparable with regular Python modules now and external caching doesn't give any advantage. If you have used a custom loader in the past have a look at the new :ref:`loader API `. Loading templates from strings In the past it was possible to generate templates from a string with the default environment configuration by using `jinja.from_string`. Jinja2 provides a :class:`Template` class that can be used to do the same, but with optional additional configuration. Automatic unicode conversion Jinja1 performed automatic conversion of bytestrings in a given encoding into unicode objects. This conversion is no longer implemented as it was inconsistent as most libraries are using the regular Python ASCII bytestring to Unicode conversion. An application powered by Jinja2 *has to* use unicode internally everywhere or make sure that Jinja2 only gets unicode strings passed. i18n Jinja1 used custom translators for internationalization. i18n is now available as Jinja2 extension and uses a simpler, more gettext friendly interface and has support for babel. For more details see :ref:`i18n-extension`. Internal methods Jinja1 exposed a few internal methods on the environment object such as `call_function`, `get_attribute` and others. While they were marked as being an internal method it was possible to override them. Jinja2 doesn't have equivalent methods. Sandbox Jinja1 was running sandbox mode by default. Few applications actually used that feature so it became optional in Jinja2. For more details about the sandboxed execution see :class:`SandboxedEnvironment`. Context Jinja1 had a stacked context as storage for variables passed to the environment. In Jinja2 a similar object exists but it doesn't allow modifications nor is it a singleton. As inheritance is dynamic now multiple context objects may exist during template evaluation. Filters and Tests Filters and tests are regular functions now. It's no longer necessary and allowed to use factory functions. Templates ~~~~~~~~~ Jinja2 has mostly the same syntax as Jinja1. What's different is that macros require parentheses around the argument list now. Additionally Jinja2 allows dynamic inheritance now and dynamic includes. The old helper function `rendertemplate` is gone now, `include` can be used instead. Includes no longer import macros and variable assignments, for that the new `import` tag is used. This concept is explained in the :ref:`import` documentation. Another small change happened in the `for`-tag. The special loop variable doesn't have a `parent` attribute, instead you have to alias the loop yourself. See :ref:`accessing-the-parent-loop` for more details. Django ------ If you have previously worked with Django templates, you should find Jinja2 very familiar. In fact, most of the syntax elements look and work the same. However, Jinja2 provides some more syntax elements covered in the documentation and some work a bit different. This section covers the template changes. As the API is fundamentally different we won't cover it here. Method Calls ~~~~~~~~~~~~ In Django method calls work implicitly, while Jinja requires the explicit Python syntax. Thus this Django code:: {% for page in user.get_created_pages %} ... {% endfor %} ...looks like this in Jinja:: {% for page in user.get_created_pages() %} ... {% endfor %} This allows you to pass variables to the method, which is not possible in Django. This syntax is also used for macros. Filter Arguments ~~~~~~~~~~~~~~~~ Jinja2 provides more than one argument for filters. Also the syntax for argument passing is different. A template that looks like this in Django:: {{ items|join:", " }} looks like this in Jinja2:: {{ items|join(', ') }} It is a bit more verbose, but it allows different types of arguments - including variables - and more than one of them. Tests ~~~~~ In addition to filters there also are tests you can perform using the is operator. Here are some examples:: {% if user.user_id is odd %} {{ user.username|e }} is odd {% else %} hmm. {{ user.username|e }} looks pretty normal {% endif %} Loops ~~~~~ For loops work very similarly to Django, but notably the Jinja2 special variable for the loop context is called `loop`, not `forloop` as in Django. In addition, the Django `empty` argument is called `else` in Jinja2. For example, the Django template:: {% for item in items %} {{ item }} {% empty %} No items! {% endfor %} ...looks like this in Jinja2:: {% for item in items %} {{ item }} {% else %} No items! {% endfor %} Cycle ~~~~~ The ``{% cycle %}`` tag does not exist in Jinja2; however, you can achieve the same output by using the `cycle` method on the loop context special variable. The following Django template:: {% for user in users %}
  • {{ user }}
  • {% endfor %} ...looks like this in Jinja2:: {% for user in users %}
  • {{ user }}
  • {% endfor %} There is no equivalent of ``{% cycle ... as variable %}``. Mako ---- .. highlight:: html+mako If you have used Mako so far and want to switch to Jinja2 you can configure Jinja2 to look more like Mako: .. sourcecode:: python env = Environment('<%', '%>', '${', '}', '<%doc>', '', '%', '##') With an environment configured like that, Jinja2 should be able to interpret a small subset of Mako templates. Jinja2 does not support embedded Python code, so you would have to move that out of the template. The syntax for defs (which are called macros in Jinja2) and template inheritance is different too. The following Mako template:: <%inherit file="layout.html" /> <%def name="title()">Page Title
      % for item in list:
    • ${item}
    • % endfor
    Looks like this in Jinja2 with the above configuration:: <% extends "layout.html" %> <% block title %>Page Title<% endblock %> <% block body %>
      % for item in list:
    • ${item}
    • % endfor
    <% endblock %> PKê|>]:õ³¯ Õ Õhtml/_sources/templates.rst.txtnu„[µü¤Template Designer Documentation =============================== .. highlight:: html+jinja This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible, the configuration from the application can be slightly different from the code presented here in terms of delimiters and behavior of undefined values. Synopsis -------- A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: ``.html``, ``.xml``, or any other extension is just fine. A template contains **variables** and/or **expressions**, which get replaced with values when a template is *rendered*; and **tags**, which control the logic of the template. The template syntax is heavily inspired by Django and Python. Below is a minimal template that illustrates a few basics using the default Jinja configuration. We will cover the details later in this document:: My Webpage

    My Webpage

    {{ a_variable }} {# a comment #} The following example shows the default configuration settings. An application developer can change the syntax configuration from ``{% foo %}`` to ``<% foo %>``, or something similar. There are a few kinds of delimiters. The default Jinja delimiters are configured as follows: * ``{% ... %}`` for :ref:`Statements ` * ``{{ ... }}`` for :ref:`Expressions` to print to the template output * ``{# ... #}`` for :ref:`Comments` not included in the template output * ``# ... ##`` for :ref:`Line Statements ` .. _variables: Variables --------- Template variables are defined by the context dictionary passed to the template. You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable. You can use a dot (``.``) to access attributes of a variable in addition to the standard Python ``__getitem__`` "subscript" syntax (``[]``). The following lines do the same thing:: {{ foo.bar }} {{ foo['bar'] }} It's important to know that the outer double-curly braces are *not* part of the variable, but the print statement. If you access variables inside tags don't put the braces around them. If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated over, and to fail for every other operation. .. _notes-on-subscriptions: .. admonition:: Implementation For the sake of convenience, ``foo.bar`` in Jinja2 does the following things on the Python layer: - check for an attribute called `bar` on `foo` (``getattr(foo, 'bar')``) - if there is not, check for an item ``'bar'`` in `foo` (``foo.__getitem__('bar')``) - if there is not, return an undefined object. ``foo['bar']`` works mostly the same with a small difference in sequence: - check for an item ``'bar'`` in `foo`. (``foo.__getitem__('bar')``) - if there is not, check for an attribute called `bar` on `foo`. (``getattr(foo, 'bar')``) - if there is not, return an undefined object. This is important if an object has an item and attribute with the same name. Additionally, the :func:`attr` filter only looks up attributes. .. _filters: Filters ------- Variables can be modified by **filters**. Filters are separated from the variable by a pipe symbol (``|``) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next. For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from variable `name` and title-case the output (``title(striptags(name))``). Filters that accept arguments have parentheses around the arguments, just like a function call. For example: ``{{ listx|join(', ') }}`` will join a list with commas (``str.join(', ', listx)``). The :ref:`builtin-filters` below describes all the builtin filters. .. _tests: Tests ----- Beside filters, there are also so-called "tests" available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add `is` plus the name of the test after the variable. For example, to find out if a variable is defined, you can do ``name is defined``, which will then return true or false depending on whether `name` is defined in the current template context. Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:: {% if loop.index is divisibleby 3 %} {% if loop.index is divisibleby(3) %} The :ref:`builtin-tests` below describes all the builtin tests. .. _comments: Comments -------- To comment-out part of a line in a template, use the comment syntax which is by default set to ``{# ... #}``. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:: {# note: commented-out template because we no longer use this {% for user in users %} ... {% endfor %} #} Whitespace Control ------------------ In the default configuration: * a single trailing newline is stripped if present * other whitespace (spaces, tabs, newlines etc.) is returned unchanged If an application configures Jinja to `trim_blocks`, the first newline after a template tag is removed automatically (like in PHP). The `lstrip_blocks` option can also be set to strip tabs and spaces from the beginning of a line to the start of a block. (Nothing will be stripped if there are other characters before the start of the block.) With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags on their own lines, and the entire block line will be removed when rendered, preserving the whitespace of the contents. For example, without the `trim_blocks` and `lstrip_blocks` options, this template::
    {% if True %} yay {% endif %}
    gets rendered with blank lines inside the div::
    yay
    But with both `trim_blocks` and `lstrip_blocks` enabled, the template block lines are removed and other whitespace is preserved::
    yay
    You can manually disable the `lstrip_blocks` behavior by putting a plus sign (``+``) at the start of a block::
    {%+ if something %}yay{% endif %}
    You can also strip whitespace in templates by hand. If you add a minus sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:: {% for item in seq -%} {{ item }} {%- endfor %} This will yield all elements without whitespace between them. If `seq` was a list of numbers from ``1`` to ``9``, the output would be ``123456789``. If :ref:`line-statements` are enabled, they strip leading whitespace automatically up to the beginning of the line. By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to `keep_trailing_newline`. .. admonition:: Note You must not add whitespace between the tag and the minus sign. **valid**:: {%- if foo -%}...{% endif %} **invalid**:: {% - if foo - %}...{% endif %} Escaping -------- It is sometimes desirable -- even necessary -- to have Jinja ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use ``{{`` as a raw string in a template and not start a variable, you have to use a trick. The easiest way to output a literal variable delimiter (``{{``) is by using a variable expression:: {{ '{{' }} For bigger sections, it makes sense to mark a block `raw`. For example, to include example Jinja syntax in a template, you can use this snippet:: {% raw %}
      {% for item in seq %}
    • {{ item }}
    • {% endfor %}
    {% endraw %} .. _line-statements: Line Statements --------------- If line statements are enabled by the application, it's possible to mark a line as a statement. For example, if the line statement prefix is configured to ``#``, the following two examples are equivalent::
      # for item in seq
    • {{ item }}
    • # endfor
      {% for item in seq %}
    • {{ item }}
    • {% endfor %}
    The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability, statements that start a block (such as `for`, `if`, `elif` etc.) may end with a colon:: # for item in seq: ... # endfor .. admonition:: Note Line statements can span multiple lines if there are open parentheses, braces or brackets::
      # for href, caption in [('index.html', 'Index'), ('about.html', 'About')]:
    • {{ caption }}
    • # endfor
    Since Jinja 2.2, line-based comments are available as well. For example, if the line-comment prefix is configured to be ``##``, everything from ``##`` to the end of the line is ignored (excluding the newline sign):: # for item in seq:
  • {{ item }}
  • ## this comment is ignored # endfor .. _template-inheritance: Template Inheritance -------------------- The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines **blocks** that child templates can override. Sounds complicated but is very basic. It's easiest to understand it by starting with an example. Base Template ~~~~~~~~~~~~~ This template, which we'll call ``base.html``, defines a simple HTML skeleton document that you might use for a simple two-column page. It's the job of "child" templates to fill the empty blocks with content:: {% block head %} {% block title %}{% endblock %} - My Webpage {% endblock %}
    {% block content %}{% endblock %}
    In this example, the ``{% block %}`` tags define four blocks that child templates can fill in. All the `block` tag does is tell the template engine that a child template may override those placeholders in the template. Child Template ~~~~~~~~~~~~~~ A child template might look like this:: {% extends "base.html" %} {% block title %}Index{% endblock %} {% block head %} {{ super() }} {% endblock %} {% block content %}

    Index

    Welcome to my awesome homepage.

    {% endblock %} The ``{% extends %}`` tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, it first locates the parent. The extends tag should be the first tag in the template. Everything before it is printed out normally and may cause confusion. For details about this behavior and how to take advantage of it, see :ref:`null-master-fallback`. The filename of the template depends on the template loader. For example, the :class:`FileSystemLoader` allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash:: {% extends "layout/default.html" %} But this behavior can depend on the application embedding Jinja. Note that since the child template doesn't define the ``footer`` block, the value from the parent template is used instead. You can't define multiple ``{% block %}`` tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a placeholder to fill - it also defines the content that fills the placeholder in the *parent*. If there were two similarly-named ``{% block %}`` tags in a template, that template's parent wouldn't know which one of the blocks' content to use. If you want to print a block multiple times, you can, however, use the special `self` variable and call the block with that name:: {% block title %}{% endblock %}

    {{ self.title() }}

    {% block body %}{% endblock %} Super Blocks ~~~~~~~~~~~~ It's possible to render the contents of the parent block by calling `super`. This gives back the results of the parent block:: {% block sidebar %}

    Table Of Contents

    ... {{ super() }} {% endblock %} Named Block End-Tags ~~~~~~~~~~~~~~~~~~~~ Jinja2 allows you to put the name of the block after the end tag for better readability:: {% block sidebar %} {% block inner_sidebar %} ... {% endblock inner_sidebar %} {% endblock sidebar %} However, the name after the `endblock` word must match the block name. Block Nesting and Scope ~~~~~~~~~~~~~~~~~~~~~~~ Blocks can be nested for more complex layouts. However, per default blocks may not access variables from outer scopes:: {% for item in seq %}
  • {% block loop_item %}{{ item }}{% endblock %}
  • {% endfor %} This example would output empty ``
  • `` items because `item` is unavailable inside the block. The reason for this is that if the block is replaced by a child template, a variable would appear that was not defined in the block or passed to the context. Starting with Jinja 2.2, you can explicitly specify that variables are available in a block by setting the block to "scoped" by adding the `scoped` modifier to a block declaration:: {% for item in seq %}
  • {% block loop_item scoped %}{{ item }}{% endblock %}
  • {% endfor %} When overriding a block, the `scoped` modifier does not have to be provided. Template Objects ~~~~~~~~~~~~~~~~ .. versionchanged:: 2.4 If a template object was passed in the template context, you can extend from that object as well. Assuming the calling code passes a layout template as `layout_template` to the environment, this code works:: {% extends layout_template %} Previously, the `layout_template` variable had to be a string with the layout template's filename for this to work. HTML Escaping ------------- When generating HTML from templates, there's always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: a. manually escaping each variable; or b. automatically escaping everything by default. Jinja supports both. What is used depends on the application configuration. The default configuration is no automatic escaping; for various reasons: - Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include HTML (e.g. numbers, booleans) which can be a huge performance hit. - The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values, the return value is double-escaped HTML. Working with Manual Escaping ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If manual escaping is enabled, it's **your** responsibility to escape variables if needed. What to escape? If you have a variable that *may* include any of the following chars (``>``, ``<``, ``&``, or ``"``) you **SHOULD** escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the ``|e`` filter:: {{ user.username|e }} Working with Automatic Escaping ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe. Variables and expressions can be marked as safe either in: a. the context dictionary by the application with `MarkupSafe.Markup`, or b. the template, with the `|safe` filter The main problem with this approach is that Python itself doesn't have the concept of tainted values; so whether a value is safe or unsafe can get lost. If a value is not marked safe, auto-escaping will take place; which means that you could end up with double-escaped contents. Double-escaping is easy to avoid, however: just rely on the tools Jinja2 provides and *don't use builtin Python constructs such as str.format or the string modulo operator (%)*. Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template data that is marked as safe. String literals in templates with automatic escaping are considered unsafe because native Python strings (``str``, ``unicode``, ``basestring``) are not `MarkupSafe.Markup` strings with an ``__html__`` attribute. .. _list-of-control-structures: List of Control Structures -------------------------- A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside ``{% ... %}`` blocks. .. _for-loop: For ~~~ Loop over each item in a sequence. For example, to display a list of users provided in a variable called `users`::

    Members

      {% for user in users %}
    • {{ user.username|e }}
    • {% endfor %}
    As variables in templates retain their object properties, it is possible to iterate over containers like `dict`::
    {% for key, value in my_dict.iteritems() %}
    {{ key|e }}
    {{ value|e }}
    {% endfor %}
    Note, however, that **Python dicts are not ordered**; so you might want to either pass a sorted ``list`` of ``tuple`` s -- or a ``collections.OrderedDict`` -- to the template, or use the `dictsort` filter. Inside of a for-loop block, you can access some special variables: +-----------------------+---------------------------------------------------+ | Variable | Description | +=======================+===================================================+ | `loop.index` | The current iteration of the loop. (1 indexed) | +-----------------------+---------------------------------------------------+ | `loop.index0` | The current iteration of the loop. (0 indexed) | +-----------------------+---------------------------------------------------+ | `loop.revindex` | The number of iterations from the end of the loop | | | (1 indexed) | +-----------------------+---------------------------------------------------+ | `loop.revindex0` | The number of iterations from the end of the loop | | | (0 indexed) | +-----------------------+---------------------------------------------------+ | `loop.first` | True if first iteration. | +-----------------------+---------------------------------------------------+ | `loop.last` | True if last iteration. | +-----------------------+---------------------------------------------------+ | `loop.length` | The number of items in the sequence. | +-----------------------+---------------------------------------------------+ | `loop.cycle` | A helper function to cycle between a list of | | | sequences. See the explanation below. | +-----------------------+---------------------------------------------------+ | `loop.depth` | Indicates how deep in a recursive loop | | | the rendering currently is. Starts at level 1 | +-----------------------+---------------------------------------------------+ | `loop.depth0` | Indicates how deep in a recursive loop | | | the rendering currently is. Starts at level 0 | +-----------------------+---------------------------------------------------+ | `loop.previtem` | The item from the previous iteration of the loop. | | | Undefined during the first iteration. | +-----------------------+---------------------------------------------------+ | `loop.nextitem` | The item from the following iteration of the loop.| | | Undefined during the last iteration. | +-----------------------+---------------------------------------------------+ | `loop.changed(*val)` | True if previously called with a different value | | | (or not called at all). | +-----------------------+---------------------------------------------------+ Within a for-loop, it's possible to cycle among a list of strings/variables each time through the loop by using the special `loop.cycle` helper:: {% for row in rows %}
  • {{ row }}
  • {% endfor %} Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound cycling. For more information, have a look at the :ref:`builtin-globals`. .. _loop-filtering: Unlike in Python, it's not possible to `break` or `continue` in a loop. You can, however, filter the sequence during iteration, which allows you to skip items. The following example skips all the users which are hidden:: {% for user in users if not user.hidden %}
  • {{ user.username|e }}
  • {% endfor %} The advantage is that the special `loop` variable will count correctly; thus not counting the users not iterated over. If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence, you can render a default block by using `else`::
      {% for user in users %}
    • {{ user.username|e }}
    • {% else %}
    • no users found
    • {% endfor %}
    Note that, in Python, `else` blocks are executed whenever the corresponding loop **did not** `break`. Since Jinja loops cannot `break` anyway, a slightly different behavior of the `else` keyword was chosen. It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or RDFa. To use loops recursively, you basically have to add the `recursive` modifier to the loop definition and call the `loop` variable with the new iterable where you want to recurse. The following example implements a sitemap with recursive loops::
      {%- for item in sitemap recursive %}
    • {{ item.title }} {%- if item.children -%} {%- endif %}
    • {%- endfor %}
    The `loop` variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind the variable `loop` by writing `{% set outer_loop = loop %}` after the loop that we want to use recursively. Then, we can call it using `{{ outer_loop(...) }}` Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope. Older versions of Jinja2 had a bug where in some circumstances it appeared that assignments would work. This is not supported. See :ref:`assignments` for more information about how to deal with this. If all you want to do is check whether some value has changed since the last iteration or will change in the next iteration, you can use `previtem` and `nextitem`:: {% for value in values %} {% if loop.previtem is defined and value > loop.previtem %} The value just increased! {% endif %} {{ value }} {% if loop.nextitem is defined and loop.nextitem > value %} The value will increase even more! {% endif %} {% endfor %} If you only care whether the value changed at all, using `changed` is even easier:: {% for entry in entries %} {% if loop.changed(entry.category) %}

    {{ entry.category }}

    {% endif %}

    {{ entry.message }}

    {% endfor %} .. _if: If ~~ The `if` statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:: {% if users %}
      {% for user in users %}
    • {{ user.username|e }}
    • {% endfor %}
    {% endif %} For multiple branches, `elif` and `else` can be used like in Python. You can use more complex :ref:`expressions` there, too:: {% if kenny.sick %} Kenny is sick. {% elif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %} If can also be used as an :ref:`inline expression ` and for :ref:`loop filtering `. .. _macros: Macros ~~~~~~ Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself ("DRY"). Here's a small example of a macro that renders a form element:: {% macro input(name, value='', type='text', size=20) -%} {%- endmacro %} The macro can then be called like a function in the namespace::

    {{ input('username') }}

    {{ input('password', type='password') }}

    If the macro was defined in a different template, you have to :ref:`import ` it first. Inside macros, you have access to three special variables: `varargs` If more positional arguments are passed to the macro than accepted by the macro, they end up in the special `varargs` variable as a list of values. `kwargs` Like `varargs` but for keyword arguments. All unconsumed keyword arguments are stored in this special variable. `caller` If the macro was called from a :ref:`call` tag, the caller is stored in this variable as a callable macro. Macros also expose some of their internal details. The following attributes are available on a macro object: `name` The name of the macro. ``{{ input.name }}`` will print ``input``. `arguments` A tuple of the names of arguments the macro accepts. `defaults` A tuple of default values. `catch_kwargs` This is `true` if the macro accepts extra keyword arguments (i.e.: accesses the special `kwargs` variable). `catch_varargs` This is `true` if the macro accepts extra positional arguments (i.e.: accesses the special `varargs` variable). `caller` This is `true` if the macro accesses the special `caller` variable and may be called from a :ref:`call` tag. If a macro name starts with an underscore, it's not exported and can't be imported. .. _call: Call ~~~~ In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special `call` block. The following example shows a macro that takes advantage of the call functionality and how it can be used:: {% macro render_dialog(title, class='dialog') -%}

    {{ title }}

    {{ caller() }}
    {%- endmacro %} {% call render_dialog('Hello World') %} This is a simple dialog rendered by using a macro and a call block. {% endcall %} It's also possible to pass arguments back to the call block. This makes it useful as a replacement for loops. Generally speaking, a call block works exactly like a macro without a name. Here's an example of how a call block can be used with arguments:: {% macro dump_users(users) -%}
      {%- for user in users %}
    • {{ user.username|e }}

      {{ caller(user) }}
    • {%- endfor %}
    {%- endmacro %} {% call(user) dump_users(list_of_user) %}
    Realname
    {{ user.realname|e }}
    Description
    {{ user.description }}
    {% endcall %} Filters ~~~~~~~ Filter sections allow you to apply regular Jinja2 filters on a block of template data. Just wrap the code in the special `filter` section:: {% filter upper %} This text becomes uppercase {% endfilter %} .. _assignments: Assignments ~~~~~~~~~~~ Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or loops) are exported from the template like top level macros and can be imported by other templates. Assignments use the `set` tag and can have multiple targets:: {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %} {% set key, value = call_something() %} .. admonition:: Scoping Behavior Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:: {% set iterated = false %} {% for item in seq %} {{ item }} {% set iterated = true %} {% endfor %} {% if not iterated %} did not iterate {% endif %} It is not possible with Jinja syntax to do this. Instead use alternative constructs like the loop else block or the special `loop` variable:: {% for item in seq %} {{ item }} {% else %} did not iterate {% endfor %} As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes:: {% set ns = namespace(found=false) %} {% for item in items %} {% if item.check_something() %} {% set ns.found = true %} {% endif %} * {{ item.title }} {% endfor %} Found item having something: {{ ns.found }} Note hat the ``obj.attr`` notation in the `set` tag is only allowed for namespace objects; attempting to assign an attribute on any other object will raise an exception. .. versionadded:: 2.10 Added support for namespace objects Block Assignments ~~~~~~~~~~~~~~~~~ .. versionadded:: 2.8 Starting with Jinja 2.8, it's possible to also use block assignments to capture the contents of a block into a variable name. This can be useful in some situations as an alternative for macros. In that case, instead of using an equals sign and a value, you just write the variable name and then everything until ``{% endset %}`` is captured. Example:: {% set navigation %}
  • Index
  • Downloads {% endset %} The `navigation` variable then contains the navigation HTML source. .. versionchanged:: 2.10 Starting with Jinja 2.10, the block assignment supports filters. Example:: {% set reply | wordwrap %} You wrote: {{ message }} {% endset %} .. _extends: Extends ~~~~~~~ The `extends` tag can be used to extend one template from another. You can have multiple `extends` tags in a file, but only one of them may be executed at a time. See the section about :ref:`template-inheritance` above. .. _blocks: Blocks ~~~~~~ Blocks are used for inheritance and act as both placeholders and replacements at the same time. They are documented in detail in the :ref:`template-inheritance` section. Include ~~~~~~~ The `include` statement is useful to include a template and return the rendered contents of that file into the current namespace:: {% include 'header.html' %} Body {% include 'footer.html' %} Included templates have access to the variables of the active context by default. For more details about context behavior of imports and includes, see :ref:`import-visibility`. From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in which case Jinja will ignore the statement if the template to be included does not exist. When combined with ``with`` or ``without context``, it must be placed *before* the context visibility statement. Here are some valid examples:: {% include "sidebar.html" ignore missing %} {% include "sidebar.html" ignore missing with context %} {% include "sidebar.html" ignore missing without context %} .. versionadded:: 2.2 You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If `ignore missing` is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception. Example:: {% include ['page_detailed.html', 'page.html'] %} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} .. versionchanged:: 2.4 If a template object was passed to the template context, you can include that object using `include`. .. _import: Import ~~~~~~ Jinja2 supports putting often used code into macros. These macros can go into different templates and get imported from there. This works similarly to the import statements in Python. It's important to know that imports are cached and imported templates don't have access to the current template variables, just the globals by default. For more details about context behavior of imports and includes, see :ref:`import-visibility`. There are two ways to import templates. You can import a complete template into a variable or request specific macros / exported variables from it. Imagine we have a helper module that renders forms (called `forms.html`):: {% macro input(name, value='', type='text') -%} {%- endmacro %} {%- macro textarea(name, value='', rows=10, cols=40) -%} {%- endmacro %} The easiest and most flexible way to access a template's variables and macros is to import the whole template module into a variable. That way, you can access the attributes:: {% import 'forms.html' as forms %}
    Username
    {{ forms.input('username') }}
    Password
    {{ forms.input('password', type='password') }}

    {{ forms.textarea('comment') }}

    Alternatively, you can import specific names from a template into the current namespace:: {% from 'forms.html' import input as input_field, textarea %}
    Username
    {{ input_field('username') }}
    Password
    {{ input_field('password', type='password') }}

    {{ textarea('comment') }}

    Macros and variables starting with one or more underscores are private and cannot be imported. .. versionchanged:: 2.4 If a template object was passed to the template context, you can import from that object. .. _import-visibility: Import Context Behavior ----------------------- By default, included templates are passed the current context and imported templates are not. The reason for this is that imports, unlike includes, are cached; as imports are often used just as a module that holds macros. This behavior can be changed explicitly: by adding `with context` or `without context` to the import/include directive, the current context can be passed to the template and caching is disabled automatically. Here are two examples:: {% from 'forms.html' import input with context %} {% include 'header.html' without context %} .. admonition:: Note In Jinja 2.0, the context that was passed to the included template did not include variables defined in the template. As a matter of fact, this did not work:: {% for box in boxes %} {% include "render_box.html" %} {% endfor %} The included template ``render_box.html`` is *not* able to access `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able to do so. .. _expressions: Expressions ----------- Jinja allows basic expressions everywhere. These work very similarly to regular Python; even if you're not working with Python you should feel comfortable with it. Literals ~~~~~~~~ The simplest form of expressions are literals. Literals are representations for Python objects such as strings and numbers. The following literals exist: "Hello World": Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template). 42 / 42.23: Integers and floating point numbers are created by just writing the number down. If a dot is present, the number is a float, otherwise an integer. Keep in mind that, in Python, ``42`` and ``42.0`` are different (``int`` and ``float``, respectively). ['list', 'of', 'objects']: Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop::
      {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'), ('downloads.html', 'Downloads')] %}
    • {{ caption }}
    • {% endfor %}
    ('tuple', 'of', 'values'): Tuples are like lists that cannot be modified ("immutable"). If a tuple only has one item, it must be followed by a comma (``('1-tuple',)``). Tuples are usually used to represent items of two or more elements. See the list example above for more details. {'dict': 'of', 'key': 'and', 'value': 'pairs'}: A dict in Python is a structure that combines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in templates; they are useful in some rare cases such as the :func:`xmlattr` filter. true / false: true is always true and false is always false. .. admonition:: Note The special constants `true`, `false`, and `none` are indeed lowercase. Because that caused confusion in the past, (`True` used to expand to an undefined variable that was considered false), all three can now also be written in title case (`True`, `False`, and `None`). However, for consistency, (all Jinja identifiers are lowercase) you should use the lowercase versions. Math ~~~~ Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness' sake. The following operators are supported: \+ Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``. \- Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``. / Divide two numbers. The return value will be a floating point number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. (Just like ``from __future__ import division``.) // Divide two numbers and return the truncated integer result. ``{{ 20 // 7 }}`` is ``2``. % Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``. \* Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would return ``4``. This can also be used to repeat a string multiple times. ``{{ '=' * 80 }}`` would print a bar of 80 equal signs. \** Raise the left operand to the power of the right operand. ``{{ 2**3 }}`` would return ``8``. Comparisons ~~~~~~~~~~~ == Compares two objects for equality. != Compares two objects for inequality. > `true` if the left hand side is greater than the right hand side. >= `true` if the left hand side is greater or equal to the right hand side. < `true` if the left hand side is lower than the right hand side. <= `true` if the left hand side is lower or equal to the right hand side. Logic ~~~~~ For `if` statements, `for` filtering, and `if` expressions, it can be useful to combine multiple expressions: and Return true if the left and the right operand are true. or Return true if the left or the right operand are true. not negate a statement (see below). (expr) group an expression. .. admonition:: Note The ``is`` and ``in`` operators support negation using an infix notation, too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar`` and ``not foo in bar``. All other expressions require a prefix notation: ``not (foo and bar).`` Other Operators ~~~~~~~~~~~~~~~ The following operators are very useful but don't fit into any of the other two categories: in Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for example, return true. is Performs a :ref:`test `. \| Applies a :ref:`filter `. ~ Converts all operands into strings and concatenates them. ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set to ``'John'``) ``Hello John!``. () Call a callable: ``{{ post.render() }}``. Inside of the parentheses you can use positional arguments and keyword arguments like in Python: ``{{ post.render(user, full=true) }}``. . / [] Get an attribute of an object. (See :ref:`variables`) .. _if-expression: If Expression ~~~~~~~~~~~~~ It is also possible to use inline `if` expressions. These are useful in some situations. For example, you can use this to extend from one template if a variable is defined, otherwise from the default layout template:: {% extends layout_template if layout_template is defined else 'master.html' %} The general syntax is `` if else ``. The `else` part is optional. If not provided, the else block implicitly evaluates into an undefined object:: .. sourcecode:: jinja {{ '[%s]' % page.title if page.title }} .. _builtin-filters: List of Builtin Filters ----------------------- .. jinjafilters:: .. _builtin-tests: List of Builtin Tests --------------------- .. jinjatests:: .. _builtin-globals: List of Global Functions ------------------------ The following functions are available in the global scope by default: .. function:: range([start,] stop[, step]) Return a list containing an arithmetic progression of integers. ``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``; start (!) defaults to ``0``. When step is given, it specifies the increment (or decrement). For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``. The end point is omitted! These are exactly the valid indices for a list of 4 elements. This is useful to repeat a template block multiple times, e.g. to fill a list. Imagine you have 7 users in the list but you want to render three empty items to enforce a height with CSS::
      {% for user in users %}
    • {{ user.username }}
    • {% endfor %} {% for number in range(10 - users|count) %}
    • ...
    • {% endfor %}
    .. function:: lipsum(n=5, html=True, min=20, max=100) Generates some lorem ipsum for the template. By default, five paragraphs of HTML are generated with each paragraph between 20 and 100 words. If html is False, regular text is returned. This is useful to generate simple contents for layout testing. .. function:: dict(\**items) A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same as ``dict(foo='bar')``. .. class:: cycler(\*items) The cycler allows you to cycle among values similar to how `loop.cycle` works. Unlike `loop.cycle`, you can use this cycler outside of loops or over multiple loops. This can be very useful if you want to show a list of folders and files with the folders on top but both in the same list with alternating row colors. The following example shows how `cycler` can be used:: {% set row_class = cycler('odd', 'even') %}
      {% for folder in folders %}
    • {{ folder|e }}
    • {% endfor %} {% for filename in files %}
    • {{ filename|e }}
    • {% endfor %}
    A cycler has the following attributes and methods: .. method:: reset() Resets the cycle to the first item. .. method:: next() Goes one item ahead and returns the then-current item. .. attribute:: current Returns the current item. .. versionadded:: 2.1 .. class:: joiner(sep=', ') A tiny helper that can be used to "join" multiple sections. A joiner is passed a string and will return that string every time it's called, except the first time (in which case it returns an empty string). You can use this to join things:: {% set pipe = joiner("|") %} {% if categories %} {{ pipe() }} Categories: {{ categories|join(", ") }} {% endif %} {% if author %} {{ pipe() }} Author: {{ author() }} {% endif %} {% if can_edit %} {{ pipe() }} Edit {% endif %} .. versionadded:: 2.1 .. class:: namespace(...) Creates a new container that allows attribute assignment using the ``{% set %}`` tag:: {% set ns = namespace() %} {% set ns.foo = 'bar' %} The main purpose of this is to allow carrying a value from within a loop body to an outer scope. Initial values can be provided as a dict, as keyword arguments, or both (same behavior as Python's `dict` constructor):: {% set ns = namespace(found=false) %} {% for item in items %} {% if item.check_something() %} {% set ns.found = true %} {% endif %} * {{ item.title }} {% endfor %} Found item having something: {{ ns.found }} .. versionadded:: 2.10 Extensions ---------- The following sections cover the built-in Jinja2 extensions that may be enabled by an application. An application could also provide further extensions not covered by this documentation; in which case there should be a separate document explaining said :ref:`extensions `. .. _i18n-in-templates: i18n ~~~~ If the i18n extension is enabled, it's possible to mark parts in the template as translatable. To mark a section as translatable, you can use `trans`::

    {% trans %}Hello {{ user }}!{% endtrans %}

    To translate a template expression --- say, using template filters, or by just accessing an attribute of an object --- you need to bind the expression to a name for use within the translation block::

    {% trans user=user.username %}Hello {{ user }}!{% endtrans %}

    If you need to bind more than one expression inside a `trans` tag, separate the pieces with a comma (``,``):: {% trans book_title=book.title, author=author.name %} This is {{ book_title }} by {{ author }} {% endtrans %} Inside trans tags no statements are allowed, only variable tags are. To pluralize, specify both the singular and plural forms with the `pluralize` tag, which appears between `trans` and `endtrans`:: {% trans count=list|length %} There is {{ count }} {{ name }} object. {% pluralize %} There are {{ count }} {{ name }} objects. {% endtrans %} By default, the first variable in a block is used to determine the correct singular or plural form. If that doesn't work out, you can specify the name which should be used for pluralizing by adding it as parameter to `pluralize`:: {% trans ..., user_count=users|length %}... {% pluralize user_count %}...{% endtrans %} When translating longer blocks of text, whitespace and linebreaks result in rather ugly and error-prone translation strings. To avoid this, a trans block can be marked as trimmed which will replace all linebreaks and the whitespace surrounding them with a single space and remove leading/trailing whitespace:: {% trans trimmed book_title=book.title %} This is {{ book_title }}. You should read it! {% endtrans %} If trimming is enabled globally, the `notrimmed` modifier can be used to disable it for a `trans` block. .. versionadded:: 2.10 The `trimmed` and `notrimmed` modifiers have been added. It's also possible to translate strings in expressions. For that purpose, three functions exist: - `gettext`: translate a single string - `ngettext`: translate a pluralizable string - `_`: alias for `gettext` For example, you can easily print a translated string like this:: {{ _('Hello World!') }} To use placeholders, use the `format` filter:: {{ _('Hello %(user)s!')|format(user=user.username) }} For multiple placeholders, always use keyword arguments to `format`, as other languages may not use the words in the same order. .. versionchanged:: 2.5 If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using placeholders is a lot easier: .. sourcecode:: html+jinja {{ gettext('Hello World!') }} {{ gettext('Hello %(name)s!', name='World') }} {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} Note that the `ngettext` function's format string automatically receives the count as a `num` parameter in addition to the regular parameters. Expression Statement ~~~~~~~~~~~~~~~~~~~~ If the expression-statement extension is loaded, a tag called `do` is available that works exactly like the regular variable expression (``{{ ... }}``); except it doesn't print anything. This can be used to modify lists:: {% do navigation.append('a string') %} Loop Controls ~~~~~~~~~~~~~ If the application enables the :ref:`loopcontrols-extension`, it's possible to use `break` and `continue` in loops. When `break` is reached, the loop is terminated; if `continue` is reached, the processing is stopped and continues with the next iteration. Here's a loop that skips every second item:: {% for user in users %} {%- if loop.index is even %}{% continue %}{% endif %} ... {% endfor %} Likewise, a loop that stops processing after the 10th iteration:: {% for user in users %} {%- if loop.index >= 10 %}{% break %}{% endif %} {%- endfor %} Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0 (See: :ref:`for-loop`). With Statement ~~~~~~~~~~~~~~ .. versionadded:: 2.3 The with statement makes it possible to create a new inner scope. Variables set within this scope are not visible outside of the scope. With in a nutshell:: {% with %} {% set foo = 42 %} {{ foo }} foo is 42 here {% endwith %} foo is not visible here any longer Because it is common to set variables at the beginning of the scope, you can do that within the `with` statement. The following two examples are equivalent:: {% with foo = 42 %} {{ foo }} {% endwith %} {% with %} {% set foo = 42 %} {{ foo }} {% endwith %} An important note on scoping here. In Jinja versions before 2.9 the behavior of referencing one variable to another had some unintended consequences. In particular one variable could refer to another defined in the same with block's opening statement. This caused issues with the cleaned up scoping behavior and has since been improved. In particular in newer Jinja2 versions the following code always refers to the variable `a` from outside the `with` block:: {% with a={}, b=a.attribute %}...{% endwith %} In earlier Jinja versions the `b` attribute would refer to the results of the first attribute. If you depend on this behavior you can rewrite it to use the ``set`` tag:: {% with a={} %} {% set b = a.attribute %} {% endwith %} .. admonition:: Extension In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It's now enabled by default. .. _autoescape-overrides: Autoescape Overrides -------------------- .. versionadded:: 2.4 If you want you can activate and deactivate the autoescaping from within the templates. Example:: {% autoescape true %} Autoescaping is active within this block {% endautoescape %} {% autoescape false %} Autoescaping is inactive within this block {% endautoescape %} After an `endautoescape` the behavior is reverted to what it was before. .. admonition:: Extension In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It's now enabled by default. PKê|>]¤²Ü›� � html/_sources/tricks.rst.txtnu„[µü¤Tips and Tricks =============== .. highlight:: html+jinja This part of the documentation shows some tips and tricks for Jinja2 templates. .. _null-master-fallback: Null-Master Fallback -------------------- Jinja2 supports dynamic inheritance and does not distinguish between parent and child template as long as no `extends` tag is visited. While this leads to the surprising behavior that everything before the first `extends` tag including whitespace is printed out instead of being ignored, it can be used for a neat trick. Usually child templates extend from one template that adds a basic HTML skeleton. However it's possible to put the `extends` tag into an `if` tag to only extend from the layout template if the `standalone` variable evaluates to false which it does per default if it's not defined. Additionally a very basic skeleton is added to the file so that if it's indeed rendered with `standalone` set to `True` a very basic HTML skeleton is added:: {% if not standalone %}{% extends 'master.html' %}{% endif -%} {% block title %}The Page Title{% endblock %} {% block body %}

    This is the page body.

    {% endblock %} Alternating Rows ---------------- If you want to have different styles for each row of a table or list you can use the `cycle` method on the `loop` object::
      {% for row in rows %}
    • {{ row }}
    • {% endfor %}
    `cycle` can take an unlimited amount of strings. Each time this tag is encountered the next item from the list is rendered. Highlighting Active Menu Items ------------------------------ Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of `block`\s in child templates are global and executed before the layout template is evaluated it's possible to define the active menu item in the child template:: {% extends "layout.html" %} {% set active_page = "index" %} The layout template can then access `active_page`. Additionally it makes sense to define a default for that variable:: {% set navigation_bar = [ ('/', 'index', 'Index'), ('/downloads/', 'downloads', 'Downloads'), ('/about/', 'about', 'About') ] -%} {% set active_page = active_page|default('index') -%} ... ... .. _accessing-the-parent-loop: Accessing the parent Loop ------------------------- The special `loop` variable always points to the innermost loop. If it's desired to have access to an outer loop it's possible to alias it:: {% for row in table %} {% set rowloop = loop %} {% for cell in row %} {% endfor %} {% endfor %}
    {{ cell }}
    PKê|>]<>¡¡html/_static/ajax-loader.gifnu„[µü¤GIF89aòÿÿÿU|ÆÖßN€�U|l–®Š«¾™¶Æ!þCreated with ajaxload.info!ù !ÿ NETSCAPE2.0,3ºÜþ0ÊIkc:œN˜f E±1º™Á¶.`ÄÂqÐ-[9ݦ9 JkçH!ù ,4ºÜþNŒ! „ »°æŠDqBQT`1 `LE[¨|µußía€ ×â†C²%$*!ù ,6º2#+ÊAÈ�Ì”V/…côNñIBa˜«pð ̳½ƨ+YíüƒÃ2©dŸ¿!ù ,3ºb%+Ê2†‘ìœV_…‹¦ …! 1D‡aªF‚°ÑbR]ó=08,�Ȥr9L!ù ,2ºr'+JçdðóL� &vÃ`\bT”…„¹hYB)ÏÊ@é<Ã&,�ȤR’!ù ,3º Â�9ãtç¼Úž0Çà!.B¶�ÊW¬¢1  sa»°5÷•�0° ‰»Ÿm)J!ù ,2ºÜþð ÙœU]šîÚqp•`ˆÝaœÝ4–…AFÅ0�`›¶ Â@›1€ÂÖΑ!ù ,2ºÜþ0ÊI«eBÔœ)×à ŽÇq10©Ê°®PÂaVÚ¥ ub‚ž[�;PKê|>] Д)Ü)Ü)html/_static/basic.cssnu„[µü¤/* * basic.css * ~~~~~~~~~ * * Sphinx stylesheet -- basic theme. * * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* -- main layout ----------------------------------------------------------- */ div.clearer { clear: both; } /* -- relbar ---------------------------------------------------------------- */ div.related { width: 100%; font-size: 90%; } div.related h3 { display: none; } div.related ul { margin: 0; padding: 0 0 0 10px; list-style: none; } div.related li { display: inline; } div.related li.right { float: right; margin-right: 5px; } /* -- sidebar --------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 10px 5px 0 10px; } div.sphinxsidebar { float: left; width: 230px; margin-left: -100%; font-size: 90%; word-wrap: break-word; overflow-wrap : break-word; } div.sphinxsidebar ul { list-style: none; } div.sphinxsidebar ul ul, div.sphinxsidebar ul.want-points { margin-left: 20px; list-style: square; } div.sphinxsidebar ul ul { margin-top: 0; margin-bottom: 0; } div.sphinxsidebar form { margin-top: 10px; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } div.sphinxsidebar #searchbox input[type="text"] { float: left; width: 80%; padding: 0.25em; box-sizing: border-box; } div.sphinxsidebar #searchbox input[type="submit"] { float: left; width: 20%; border-left: none; padding: 0.25em; box-sizing: border-box; } img { border: 0; max-width: 100%; } /* -- search page ----------------------------------------------------------- */ ul.search { margin: 10px 0 0 20px; padding: 0; } ul.search li { padding: 5px 0 5px 20px; background-image: url(file.png); background-repeat: no-repeat; background-position: 0 7px; } ul.search li a { font-weight: bold; } ul.search li div.context { color: #888; margin: 2px 0 0 30px; text-align: left; } ul.keywordmatches li.goodmatch a { font-weight: bold; } /* -- index page ------------------------------------------------------------ */ table.contentstable { width: 90%; margin-left: auto; margin-right: auto; } table.contentstable p.biglink { line-height: 150%; } a.biglink { font-size: 1.3em; } span.linkdescr { font-style: italic; padding-top: 5px; font-size: 90%; } /* -- general index --------------------------------------------------------- */ table.indextable { width: 100%; } table.indextable td { text-align: left; vertical-align: top; } table.indextable ul { margin-top: 0; margin-bottom: 0; list-style-type: none; } table.indextable > tbody > tr > td > ul { padding-left: 0em; } table.indextable tr.pcap { height: 10px; } table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2; } img.toggler { margin-right: 3px; margin-top: 3px; cursor: pointer; } div.modindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } div.genindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } /* -- domain module index --------------------------------------------------- */ table.modindextable td { padding: 2px; border-collapse: collapse; } /* -- general body styles --------------------------------------------------- */ div.body { min-width: 450px; max-width: 800px; } div.body p, div.body dd, div.body li, div.body blockquote { -moz-hyphens: auto; -ms-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } a.headerlink { visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink, caption:hover > a.headerlink, p.caption:hover > a.headerlink, div.code-block-caption:hover > a.headerlink { visibility: visible; } div.body p.caption { text-align: inherit; } div.body td { text-align: left; } .first { margin-top: 0 !important; } p.rubric { margin-top: 30px; font-weight: bold; } img.align-left, .figure.align-left, object.align-left { clear: left; float: left; margin-right: 1em; } img.align-right, .figure.align-right, object.align-right { clear: right; float: right; margin-left: 1em; } img.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left; } .align-center { text-align: center; } .align-right { text-align: right; } /* -- sidebars -------------------------------------------------------------- */ div.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; padding: 7px 7px 0 7px; background-color: #ffe; width: 40%; float: right; } p.sidebar-title { font-weight: bold; } /* -- topics ---------------------------------------------------------------- */ div.topic { border: 1px solid #ccc; padding: 7px 7px 0 7px; margin: 10px 0 10px 0; } p.topic-title { font-size: 1.1em; font-weight: bold; margin-top: 10px; } /* -- admonitions ----------------------------------------------------------- */ div.admonition { margin-top: 10px; margin-bottom: 10px; padding: 7px; } div.admonition dt { font-weight: bold; } div.admonition dl { margin-bottom: 0; } p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; } div.body p.centered { text-align: center; margin-top: 25px; } /* -- tables ---------------------------------------------------------------- */ table.docutils { border: 0; border-collapse: collapse; } table.align-center { margin-left: auto; margin-right: auto; } table caption span.caption-number { font-style: italic; } table caption span.caption-text { } table.docutils td, table.docutils th { padding: 1px 8px 1px 5px; border-top: 0; border-left: 0; border-right: 0; border-bottom: 1px solid #aaa; } table.footnote td, table.footnote th { border: 0 !important; } th { text-align: left; padding-right: 5px; } table.citation { border-left: solid 1px gray; margin-left: 1px; } table.citation td { border-bottom: none; } /* -- figures --------------------------------------------------------------- */ div.figure { margin: 0.5em; padding: 0.5em; } div.figure p.caption { padding: 0.3em; } div.figure p.caption span.caption-number { font-style: italic; } div.figure p.caption span.caption-text { } /* -- field list styles ----------------------------------------------------- */ table.field-list td, table.field-list th { border: 0 !important; } .field-list ul { margin: 0; padding-left: 1em; } .field-list p { margin: 0; } .field-name { -moz-hyphens: manual; -ms-hyphens: manual; -webkit-hyphens: manual; hyphens: manual; } /* -- other body styles ----------------------------------------------------- */ ol.arabic { list-style: decimal; } ol.loweralpha { list-style: lower-alpha; } ol.upperalpha { list-style: upper-alpha; } ol.lowerroman { list-style: lower-roman; } ol.upperroman { list-style: upper-roman; } dl { margin-bottom: 15px; } dd p { margin-top: 0px; } dd ul, dd table { margin-bottom: 10px; } dd { margin-top: 3px; margin-bottom: 10px; margin-left: 30px; } dt:target, span.highlighted { background-color: #fbe54e; } rect.highlighted { fill: #fbe54e; } dl.glossary dt { font-weight: bold; font-size: 1.1em; } .optional { font-size: 1.3em; } .sig-paren { font-size: larger; } .versionmodified { font-style: italic; } .system-message { background-color: #fda; padding: 5px; border: 3px solid red; } .footnote:target { background-color: #ffa; } .line-block { display: block; margin-top: 1em; margin-bottom: 1em; } .line-block .line-block { margin-top: 0; margin-bottom: 0; margin-left: 1.5em; } .guilabel, .menuselection { font-family: sans-serif; } .accelerator { text-decoration: underline; } .classifier { font-style: oblique; } abbr, acronym { border-bottom: dotted 1px; cursor: help; } /* -- code displays --------------------------------------------------------- */ pre { overflow: auto; overflow-y: hidden; /* fixes display issues on Chrome browsers */ } span.pre { -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; } td.linenos pre { padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } table.highlighttable { margin-left: 0.5em; } table.highlighttable td { padding: 0 0.5em 0 0.5em; } div.code-block-caption { padding: 2px 5px; font-size: small; } div.code-block-caption code { background-color: transparent; } div.code-block-caption + div > div.highlight > pre { margin-top: 0; } div.code-block-caption span.caption-number { padding: 0.1em 0.3em; font-style: italic; } div.code-block-caption span.caption-text { } div.literal-block-wrapper { padding: 1em 1em 0; } div.literal-block-wrapper div.highlight { margin: 0; } code.descname { background-color: transparent; font-weight: bold; font-size: 1.2em; } code.descclassname { background-color: transparent; } code.xref, a code { background-color: transparent; font-weight: bold; } h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { background-color: transparent; } .viewcode-link { float: right; } .viewcode-back { float: right; font-family: sans-serif; } div.viewcode-block:target { margin: -1px -10px; padding: 0 10px; } /* -- math display ---------------------------------------------------------- */ img.math { vertical-align: middle; } div.body div.math p { text-align: center; } span.eqno { float: right; } span.eqno a.headerlink { position: relative; left: 0px; z-index: 1; } div.math:hover a.headerlink { visibility: visible; } /* -- printout stylesheet --------------------------------------------------- */ @media print { div.document, div.documentwrapper, div.bodywrapper { margin: 0 !important; width: 100%; } div.sphinxsidebar, div.related, div.footer, #top-link { display: none; } }PKê|>]x,Ëôôhtml/_static/comment-bright.pngnu„[µü¤‰PNG  IHDRóÿa»IDATx…“Àä<†ß™¤ÝýmÛ¶mÛ¶q¶mÛ¶mÛ¶m£ÚMæš=û‰�óD¡¹8ÈãôtÙ�·\{óïÕÙôÛ56ýÿj¥�Ÿ>QnÝ~3úœŠ»sÌDš{ÛÞúo»­S+Ù»»Ø€=’·Çnù³Ónù¡ÍWÂ?ÚîXumŽùóA•ÅHóIµ%pHså�c‘æ‰ÖYoã¤ošíØ_{‰µµZ)48sõÚ³ïßöÛ—ßðû„Ê8Y�üYsóàj3�ÄÁ4ä¶s^¸#Ç’ûðtË‹q˜kZà´ÜœwíÝ¿´ßµ>ŽÂ!¸«áù8ŽßpVnü{úÕ·ü=ån$ªûp\å^;=�’;µ�wPIEND®B`‚PKê|>]5†ú==html/_static/comment-close.pngnu„[µü¤‰PNG  IHDRóÿaIDATxmΜõ8†ñ÷$íkó³mÛ¶mÛ¶mÛ¶mÛ¶ÝAïMÎfp×ÿþž:€Oæ®'eð$Q¹qÏ —ÿ´aáÑO[ú¤Bæ�3‡Uß÷9þO²Ög+Å‚-¾81dû‡w=7¿ç«ßq“¥ï¸öü×1¹�¼¾ûCëK�a”~ ±Ê�¼Žû<ÎÔeÍ›è‰ÝgË'ÝyÃ{ÝråGn°ä×_öžë.|Ë5½Õ­Ì„Y‡¹ ²l›Ï•§¶¥]’Õ‚‘´ÓíÒÉ…®O�4”‚ƒlØ!AÁ@@àwã²ôn�Ÿ�íy½�^¤òÂxa*�ž;1’u¾SºÑüWºÝ¦O<þ*ë‰7˜g>bž~ŸyÞž»ü mNÖ³É\£(Žtëë›:+ó¼tU&>9Z}æëOã®k=îŠæ®ÛwÔˆ=Žîe€ãûhjo �OÚî÷àSd̳m#Ï(®2ôÚ®�‰Šöˆ&ë!Q&Çô<þþ­iá_~ëð Yþ ¡»=�º¼¨KâeߨOÄ™Ó Ó)Ó\Ó/&þí—f§¾û½ÙñdðåÇÀ’øUû¶Ì@Æøw‘Ôyq€#ý9½IEND®B`‚PKê|>]4³ÿ ��html/_static/comment.pngnu„[µü¤‰PNG  IHDRóÿaHIDATx…�Œ_Æç�ÚVTÛVܰŽQǵ«FT7ªm»]ïì<�ÍMƒÚí½=ç>$ë“|¹ü~\>&nM²õðáKÿ<+W ú¬7‚¶â¯­zÉ« Ÿ–ÉÏ?Œwâê‹!«¶ž8_ÑO­ ÙðÞ§4—&‡ ¢MËSê'Ÿ±­/Ò›ñïœ=rÖ¼`ŸÂVÈ0!©¸?t'$Ý#°'‚äP`¤•iawPáÚœºÁ÷ƒ¬?DãqÙ�Ì.`Ž ¡lZ%9A Ð{EÒº !;eš`fšT]’P]ZCD‰­ÌX¤2e)ן§Ûr¯y­OZs߂Ј {š1<¦”†*€Bx‘µôᯠà`Êã²û�(¬B4ƒš2|šÖk@°•à�À=¯P¦A¿™ÙÈše;  HÍ­²U‚íà`¿Bõ£¹‡ÅÒ@(é”IàÁÏšRÝ ©áF¸"¨aí(.Î |R*wãÎÞZB/bZ÷ f‡ÏM¦Q+ˆ¨d!ŠÍÚ!06«•ê5.÷‹Ä9Eq+@3 Ù‰ª©VSˈêd8£â˜Ì;ŸÐ&KpHh0€f;€±ÊhãY¹,]|ïÁLcne!Ý¿fë‰KcJâFiyÒüŒöüS��O‚hëמ%ws ÅèívaÿºJ{¨ÁßÚ£;/S3ï½Î ?q¥¢cáC¯Ó\ƒq¯H­ø¯xíÑñsem¹±‚k2n]JOžS$$html/_static/doctools.jsnu„[µü¤/* * doctools.js * ~~~~~~~~~~~ * * Sphinx JavaScript utilities for all documentation. * * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /** * select a different prefix for underscore */ $u = _.noConflict(); /** * make the code below compatible with browsers without * an installed firebug like debugger if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } */ /** * small helper function to urldecode strings */ jQuery.urldecode = function(x) { return decodeURIComponent(x).replace(/\+/g, ' '); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node, addItems) { if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className) && !jQuery(node.parentNode).hasClass("nohighlight")) { var span; var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); if (isInSVG) { span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); } else { span = document.createElement("span"); span.className = className; } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); if (isInSVG) { var bbox = span.getBBox(); var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); rect.x.baseVal.value = bbox.x; rect.y.baseVal.value = bbox.y; rect.width.baseVal.value = bbox.width; rect.height.baseVal.value = bbox.height; rect.setAttribute('class', className); var parentOfText = node.parentNode.parentNode; addItems.push({ "parent": node.parentNode, "target": rect}); } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this, addItems); }); } } var addItems = []; var result = this.each(function() { highlight(this, addItems); }); for (var i = 0; i < addItems.length; ++i) { jQuery(addItems[i].parent).before(addItems[i].target); } return result; }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } /** * Small JavaScript module for the documentation. */ var Documentation = { init : function() { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); }, /** * i18n support */ TRANSLATIONS : {}, PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; if (typeof translated === 'undefined') return string; return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, addTranslations : function(catalog) { for (var key in catalog.messages) this.TRANSLATIONS[key] = catalog.messages[key]; this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); this.LOCALE = catalog.locale; }, /** * add context elements like header anchor links */ addContextElements : function() { $('div[id] > :header:first').each(function() { $('\u00B6'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('\u00B6'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }, /** * workaround a firefox stupidity * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); }, /** * highlight the search words provided in the url in the text */ highlightSearchWords : function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); if (!body.length) { body = $('body'); } window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlighted'); }); }, 10); $('') .appendTo($('#searchbox')); } }, /** * init the domain index toggle buttons */ initIndexTable : function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }, /** * helper function to hide the search marks again */ hideSearchWords : function() { $('#searchbox .highlight-link').fadeOut(300); $('span.highlighted').removeClass('highlighted'); }, /** * make the url absolute */ makeURL : function(relativeURL) { return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; }, /** * get the current relative url */ getCurrentURL : function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); }, initOnKeyListeners: function() { $(document).keyup(function(event) { var activeElementType = document.activeElement.tagName; // don't navigate when in search box or textarea if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { switch (event.keyCode) { case 37: // left var prevHref = $('link[rel="prev"]').prop('href'); if (prevHref) { window.location.href = prevHref; return false; } case 39: // right var nextHref = $('link[rel="next"]').prop('href'); if (nextHref) { window.location.href = nextHref; return false; } } } }); } }; // quick alias for translations _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); });PKê|>]>¾ta%html/_static/documentation_options.jsnu„[µü¤var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), VERSION: '2.10.1', LANGUAGE: 'None', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' };PKê|>]„'»ÞÞhtml/_static/down-pressed.pngnu„[µü¤‰PNG  IHDRóÿa¥IDATxcØÏÌ@ëJ@lK†f[�^g%_â æÁ£‰ªæ HºäK þÄ¿�øâD އ²Aåþ�Ôb3݈ÿCüGÇhr.¸œx¤€¾‚/`X€ø WüƒÊ± Ý2 ¯ ØeÄFÑ+,.xEJ ñ¨Íÿ lARÊ $ÛW�›T?‚0iÝ„)1€mƒÎ¿ÏaUï°IEND®B`‚PKê|>]9.¡ÂÊÊhtml/_static/down.pngnu„[µü¤‰PNG  IHDRµú7ê‘IDATx­Œµ¡ƒP@ï—îû ì@IÇß—`&˜"z6xK@kbÏ¢x•s]…éÁM ˆ:Ç�Š/ž+£g¾Pdç2G³eÃ�~�߸J“_÷c S_Åå— S%exdUú¡]õ(UHüàò>‘&—…´Á;4Úùi‡ã$•n˜3—> ûy”céñ„¯d„ÚIEND®B`‚PKê|>]S[¯Shtml/_static/file.pngnu„[µü¤‰PNG  IHDRóÿaåIDATx­“ƒR…÷){…l× Û¶ÙfÛ=@®å œ:¿¹¾3ßú~箄þþþ¹òòrX$AðX-öD ~ñýý òóó€Ç‰(ŠP%¾€�8<<9:: ãøøØP•êO&’$é Ø�l~‚X÷ìã�ûæ&ȽÖEWÀ^4µwQ}ÂÎö^ü˜Ô÷Í£¾ ‹¨iê©ïš0/H/é@F)éDzq+’ój�”[žSU5¾€Ìèhš¦/ð¿oY– G&Lfs|�£¡»»{Íêßøß3%¸U+S°é`AFÒIEND®B`‚PKê|>]5Qçô(ô(html/_static/jinja-small.pngnu„[µü¤‰PNG  IHDR´ªeÙsBIT|dˆ pHYs~~[ªÈtEXtSoftwarewww.inkscape.org›î< IDATxœí�y°,GuæÝw}»Þ{Z�6°ØA„Yð€ Ã` 0`†0‹˜™Á0€ ^f 6a›!†Á6�0›adÆÌ"–C 0F I0hyBOzÒ»Û»}{þÈ̾ÙÙ™Y™UÕ}ï}ê/¢¢«2«3³ª¾:uòäÉ“�~¿ÏSìDˆÈð\à?SJýNgJè)vDäàeÀ+�»9Y8»5MšbŠrˆÈ9À«€_öôû}:�Ž=¥7•ÐSlkˆÈ ðT´D~ ÐMd»ÍÌÌØÓ/šzŠm ¹Z¿8Û¦»Dèt:t»]€QJ]0U9¦Ø6‘ð$´4~:0 £$vá¨ÁþaŠ)¶"rð"à¥Àù6=Ed ‡Ð˜ªSlDäqÀ%À3�y›¾±±‘$1h"Û ø‘Rê<˜Jè)& 9¼­VÜצçHc‹n·ëJæÛ€7Ùƒ)¡§;ŒÝø—�g¡uä"iìÃ�¹¼x«Rê¶AÞTå˜b‘h?�Ä%ÒØ‡cÕ¸F)u¾Ÿ?•ÐS´Câ§£IüdZ"qÿJœJè)ADö³Iâ_d¼$°)kÀ9J©ܼ©„ž¢‰Ÿ…&ñ‚͉]˜áîy´/Çëܼ©„ž" "²�Mÿ&± G�¾ 8[)u§Í›Jè)¢‘{Ož�–Ä‹6oÒ$vaëít:§ ‡ÆÿÔæM%ôˆÈYÀÌöDà<7+IìÑÒ×ç+¥Öa*¡ïÒ0CÎ�g“ĆÎÛ.$váHé{ÏÞB‹È™J©'ÝÀ)Æ 9x ð ó+À€Nèü*ÿ‰í@pÇú71„Q9DäåÀÞ¼_)õý ·sŠ‘Eàþ “÷AÀé±ÿ8ÃÈ#D-=ž4_è'+¥>"ôÙh½Äâ[hrP)õ㉴rŠ D¤ œÜ¸»Ùîáüž œ Ì„þï7EâPš{¼�HíèÒŸVJ=9Ø)‘F¿Ù.úÀ×€ÿ |PJ©­ÿîœ$0’õn Ôý½;pýKV×#­”´¥Ç[IjGJ?4Fè7ÿÅQ¼‡Þhƒ›�@“û2¥ÔÑ1¶yÇBDv‡Ívq²žšSžOÖPºE‰CiMˆ¼Äv¼ïÞ#ôc�Ëz½Þ ÝóAuѾŠ&÷'•RßOÓ·"2 BÓþº[,m1T^î½õïµ»#MIú8¥ó$X<>~|N)uGò�B+¯þÈæmw2·Iä¶¥´ÿß&:e)�cém¹)©_ëó•R׌4<•ÃŒB½øu¨7y1„R2o)�CàR’çž_¥;ûçT©1Õ ô¸ŽîìïG:x·¡uã�6!3)lŒÿ@;po{2�‹Èã’Ðm`Ö�qªvßÑ“¿‹V-> |Ùº6E碋.:øp1l2�Ký(IK¥çæ×E]ý¹ b�[w6÷ì}J©ç.¡1f�K�‡Ãð¨`L‚Ì'³”njÝh¢v䪩¼*5mp f�¿Æºmìt)==º uõ禶ç�8÷¼È‹ðSà3·¡6ºÀŸW‚öZ²[·Ûl e~UĨ³_'/vúÕy¡¼ÜûQŠœòSmNÝ›–{\ò öß§”jn:‹ «”ê¡£¢탱f`7—Ü.á}¤È•ÊoCýhrì_o,=—äu·œ²KÚÜä8´ŸÊËý?cT7€èÀÊà^À¹À9�ßC0ꉗ»ß6™sÎË9?•–“7´=€â§M²áìS)uÑHƒZDpè[)uøžÙF "_ÑéŒk¼©#vÎq,-•^zN 1âºåÆîu‰®lÓruâT^NÇÑ«{¬ÒÌz5ð1K\‹q».ésÕ�PZ¬½9êB rÊÌU1Bi©ûç×U3úýÍ0Öüë�y=•o¬¨ëRùqàÍ�NÇ�þè·±¦nu—•Òã’Î6­M�Ms ›P‹Žß®@žŒxǵ�Ú�fDä ÀÃÐ>ÇáÂkv Æ­Kçy+uéRÝ9”^g$Ð%©/i+¸r#›ä½¸B)umêã@ãÈI"²8=_îÃ艜ºð ‚–»N9mW¥—žBÎ3h“Ľ^�^¯7BÞŒvôÑväkÌv5ÚÉþ ? èV¡ÕP`"òèXcE’wÜûuŽë¦·…˜u¢×ë±±±1´-..Ž˜QSÄ^YYa}=è:±�Vn~„ŽÁ|�³ýH)µÒäºÆ�¶C�]Š!´E“N`ûUyUçç¤×=Ï'�OTK Ÿ�>ìþÿf´ßñ³ÝjÆ%v,Ú&ôg€ÌLç6:�[-¥Ç¥G¯®®²¾¾žMXƒ[Ðð××ÏC«{Cmªê:ø¢Rê µ/b¢UB+¥–Dä³è¥lØiÄvÓlÇ´k@[ºôÒÒ’Oà>pš¨×9¿ƒ}3>0€ˆ< 8³Ó鉛²E¬U6t‡aÑG/Å#´ÅVÛïô„:C±Íbaa�={ö$Ûœ‹õõu[öõÀ‹Ñ„½^)µZX”^›ammàsãº%øÒúĉlll¸#¼SBgàRà¦t7·SÒa„M;w.™—––b ,£Ÿ¬½½„À±sOœ8aw/SJ}ºnã0Ïouuó=Ø»woTZŸ8qÂwžº J©‹È·�ÇLA!÷á§ü  ,´ïüÿz´­ôVtO>õ{+pT)µ""ŸþÕììl±Žƒó‚}®øÏÃø¯hsé^àåÀiîýL °¼ mɸºaýÛã xþ à"à`ŶËUØŽ£Ï,†:9Uê ðt¥Ô·k\Ë…~ûê�Ø%”SÖÿ«Ñž”Rïµû"ò|à´Ð×/poß­”jT÷vÅX­”úð¥ªóDd�a‚ï–€;ÝM)µdÎ'zmè"ýÙ h:¼ƒ·o¾óÎ;9pà³³£·¬Äœ×ï÷­„î¡]vÛÂ~[G…txf±÷“ [º$…éÝh¶Ü›�›ÙÙÙ!‚Ybmll :^΃�QÒž‘j—$®@ét:þ(è)u®¹;ŽÐý—LNO¿vLgo.Y[[;cyy™]»v�Ô™ƒµµ5Kè#À_•6BDÎDëËÝN§Ã®]»XXÐ º¦†»cû M ¶OBd†’…¼ñ'NG,8Cî§èNð‰`Á-bÇZDþ-ð?€Ê‰ºÀAùK´îö“ºu*¥n‘7¶ºº•ÒUwâ~¼J—4¡ÙöûÐvæ}À31Ÿö~¿ÏñãÇY\\’Š9Dö÷í}Âú¿1Òú÷ ’Ÿ¦a¾r°£-"/ÞÌÌÏϳ¸¨W{iqqÑv _í!=Õ/¿©SùîµÕMC«cǶ'´Yå]À€j2»˜™™annŽõõu;Ü~x±ˆ| -í¶Ë;¥? `yy™Ý»wײGÏÍͱoß¾ êÄGyirg¥”ÙbÌD¶[pc#´ˆ<mšºíúXüÉ1QQ?<ŦÍÍÍ�œ—"¶�näà!èiCµÐï÷¹ýöÛ9õÔð*l)‚/..Ô$·¼X=~™1ÒmG"Òv®„‘Kнq7í(šÜGÑSÚO˜ßÐþ Zšîª#Dœ±C’Ïÿl»î–¾´ IRžÝÞÄ&“Ä>‰mZÈ‹.”·�ˆl±s <Fnºõ×hUÄv¥bˆ€)é^¥ÒĈœKðT'*‡¸þñ6%²ÅŽV9Îýæææ*pŒ,®Dô÷s˨“Ÿ"vIýUHéÉUÄuÿ³]‰ìÝ“-¡÷¡/``ãò¥cˆ@9y.ÆMì’¼œv¸˜„t®“_BZ?f‡¿y˜¡[ càÂuŒwm·m;çü6òë—"ôR¶àP^Ž9t®�Ña ê5FÚBô”R±¨�³’ÿãº-%UÛ–ÈUùmHé!|ilÓBÒÚnn°ëNšOh÷———Y[[!k ôÑ�ûŸ¡}Rª~ÇÌb¢„¶h“Ø©¼:R:UfÝN¢ W Úý�„tóC’3„ýû÷³k×®¨ŠbC'xè¡§œ¥Hé§Ý®ñ;¶„Ð[AìPZŽÎî H~ž}2ºû- �žŽv»³�œSÕñsê*ðC49o«Z�u'ab„žy]¸ŸTûë§¥tÅ*‰XhŸ†c ÒßRùÇü%Dä�ÀïÆT÷ÚÑù²í*a›bâ:$ùì¯'E’¡n·›tN:vì˜. )ÖÑ×c·cÞ±M«"ä�c’†w@:Œ®s_o>YÉ  t`蹉W5îÔqZGŒ±2}»(Ä!t†ºñÓ ·m¢'¡ï„$y×Ð3¼�›ß¥Àq(ï�À «T§Þ'(¥~ÔìR¶=F$4Õ ˜º6.ž€ž¾4BÒºŸ=ãýÂXçÍÂy¸M&Çî ��”vŽ·Eçqal„VJý”ñHƒAü 1Ýý�ì™Äk ÷„ڴ%¨»hÐV"Hh o€¢�™àz’ãTÇ ´pòÎâ$ÆN$ôÈj^:™l¬ œî²>÷ƒ»M¨M[‚�Hè¡�W!ÜÅÔ HhS ½}1¢r$ôç»B‡*m_~sŸ‹È|ðÄ“'¡}Ü%ô@åpqWÔ£O*B<Öî BÈP9¼ü)¡·*%´ƒ»B‡|xèÄTx?mccƒãÇ�³¼¼ìÏIü#¥Ô'EäU0L蔤6„­×G -"ç¢Ik7!@¾Óѫך¹“àÞf{®mŽYqÁ%ù7•RcÅMZD~Ý4ì‘xŸRÛ«ömŸ®�…•NÞLæY6õËW£/øJàóèõóRk &%´•pŠty§÷H³=½¸Ï×�íJ¥ÔÈÜ.¥T_D^¼ x^¿ßgii)* ‡ØkkkÜ~ûÐWüÀ�ß3ÇQ×ÑP™sss6nö#ý<9-õöó»Ýî`ée»ï×e—^vžwø9³ýª9}CD®BüóÀ_µÕ朗З£I7 ³ç�{ìì²kfjV= åî8 E$´OdçAF?u"²ˆ–:�t¶PïÿÁf{±9^‘o¡Éý ó{•RjC)õuy!:üïýÐÁÙƒÈ C3M¾¼ø¾Éud»¸S×~>pê5À™8dîv»ìÚµ‹™™™!³`(`�m‡+Èì5ôz=7„B8Ýøh›F„$¡•Rß‘‹��¢õæ‘À'>Rr½^Ï]8ÇÅ%«›:V—s“o³;"²­ó? MÞ‡¢W¦`ff†ùùùÁ6777h¯ÝNœ8±ˆ&ƒKˆ;Œe¥øÇ€ÐëªÜx£^†ÑêÇl~¹}2=zth�E‡W*¥¾¸'Q ‚CÌ{ˆÈ·g¾2¯>eÓ666X^^fnnn°žK ìWÆsGøSàO”R?+.°•:´RꈈüðztGâiM*t.ìZà2àËÀW”R?Ìø{V§0Dht˜ÞßCú-­,qFÖ·*•¿Ê”%÷êê*ËËËôûý}è>ÂÃÑ/æ 4!–––†Úf ’ÌËË˱Ùê±~Æ�„NéÏ6offƾ( ?û(¥.‘·¢_”_}µ)ÇŠ™v-ð]¥Ô* ¨‰¬N¡YñõMFZ?ÍšRåC`áýï·”Rï+lo–§�SÇ€ÐJ©5Ó'ø hýÞJ�ýûÃÖ@wµ[çÂÂÇŽcyyÈ÷é{À³”Rv%©ï£;Ò³è/ÁÃ�×Ùrýz¸¸ í{œø\À]±¶ÇàúÞx„PJ½@DÞ<xGUç5¯#{±RêH埠Ôl7X[Ïcc$[]]�•umaÝ�¹L›Ó¶!©¦”úGùðû)�©,)=ÝZ1 ®F¿$¿éš#ͧü챈ŒÜˆ bÑy9R¨¹¤s,"÷N¬”ú‰Ô¡×ë }iB_. ³Rm¨î3ÐKÚ� ¥„¾½ã)hiùËè^}Ô -0"¡CR4¢rX¼½FàÏ€Ïöûý}1Iì–o÷Ý^¼ÁÅJ©P=>&�Lâå:Ž�t «Êw¬IB¬ÀærÔ�2RÙ%t Æ›Ñ«úŽ=ÀM¡Mot°Öœˆœ“:ß»ÐÙ"ödéÐ!•ÃB)u3¦Ó#"G€}·ÝvÛ ËÞ½{YXX!òúú:7ÝtS¨ºÜAƒ AŸí\B™íúý¾KÆ 2Ê¿xšŒkÀéÀ{3^ʾRjOFù­b,ÎIdýÆ6Á€Ð)5ǹ±U Îsº·Cж[‡ýi ø.:DÃõ/iRBÒ‹$tªl?­DB+¥n>n�Íj¶9˜È>Z%tˆdŽn×*¡Cõº¿U~oEûß ¼3ØS= .SJýJ�¶G êΩ·‘„NÛYöT9%Se²¨Šˆe±%ñóZ!t¦3PN††¾3ìÐI ­”ú_vߘ&GFÏ/I–Š!"‡^\ó��ö¥P¬Cçv ­ÚáX:¾žYh‹K¿ßïwbåì| ]�6]émç™íJ<¿†$J¨3h�«3?çS�B„û�;î:°žMYx<‡ØŽ¥ã m_Ž3씪sgHhy:fÝØt8A@z>ND¾�Y)U:‰õ¨6µ¨.Ö½ÿ•é:wÑEÛÖ™™™Áp°ëEW�tD¤ÏæZŽîvØÖj¿wpÅàB3‹f£ ?p'°·âÅÙþ„‘Ï }~‡2£ðž@yë ?9¾} *Sz‚l‰Ûâà„^ŽR•Chk!9óÌ;T•~ò—Fû¼Ìá ×[¤tè [ô͆ÝÜ0[/ñ{ª-71ík·ˆ|Ýñ~¯R*ÛUµ J%ôß`í;)ňì:žnò,zµØC¹ ÈuÂAàjYC››Nx¿~ÚÃÜ2üëq$ôœùJT·ûèûõÂÌöpøðá䀋°°i¶]9:tÄí£k¶Jn¤,MæÿÏ4ûWQà{Ý¥„þðûÀ½RÒµyºþËÄÈ #Y¨ ÞPëy…×7Ò~·�¿c6Гþoè¿J©¯ŠÈ70¡s:‚¹„t'ÄÚû›«jØýÙÙY:”6É)e ZXX`cc£Í²Q:°²."/@{“E—9®"¹OjWÒLjïþÆn¦u&:xð`PÊ…^?mnn.øâ¸*AÁâ?AõÀ-77¯JjWí§òKþ“côÜ‹W˜`«âN¡Rêr3á~^ ‘«òš¤AØaªdß•† —L;pà�N‡#GŽ„–G aΖ‘iª+"²\—عÿ)-ÏàkJ©wE k­š)½øT^[iUÒ'µûÌÇêM )¡ÝúBõ¶Mæ:9ôŸÜÿnz;9'?õ¿*rebHB‡¶P[CmÉyér÷ëä·‘6 ´>°’R ÚV-Ü´’üÔ>Äuõi´È-·ÜB§£gƒûþ×n¹kkkôz½�Êd‡©�áêh{¶#±'�F„v%E(z¼u9Œuøì¯;cÙ×}'Eä˜-Ý%¹uè/è†m�¿JÚ¯®®rüx¼eï³Kòn·Ëž=›Žm¹Ä¶®°®Z‘RKüßÐÒzÀP™“F]Bß�ì˜Á…QB4¹8ß²¸¸8°m‡ˆÜï÷9v,w0o´®½{÷²¸¸8"­766ê”{ z$o?ÚÎýá A‹«Ð>Ä�mOèer ]"¥mˆ„ºp í–¿æ:‹Z„VJ= @D|Ó¦‡Hfp5ð&`úáîKì»ió9/DH¢}ô(c=Èb£û1ýÕ»¦Uà¯Í~2žˆYßåVàV9Õ-3ïQJý�›`†¨]‚_ˆž¬0Rn‰Ê�N—2:àÛÿ`L¨8øzfüÄ06ç$ïÂŽ*¥>PZ†ˆ, ‰}ð5ϾTœü”Rw/¨ë�èy|A]Ú‘ŒG•R—”^ Ž?t¢�<ÄÎADŽÚvÖé$:ªÞ’Rêù9aêýmG1¿íN{^^Iµ ´:"ÒSL"PJ­ó9`ÄÇ!´ïzÄ ­#ßòˆNY×§{ÈÁ?fípÚŸ#lF&õ•Û©ëtÙµÒâñÇ[«°¢×[‹Ð~âóæ"ûµS;œ´ºË\TÆ«'‡`ó0ltËÊÙ7Bb†@”ÔDÙÎ%´‹ÀÅ5%ô}`4ÂflßÞ–ÌÅ�„N¤.¡m Iè€Ô¬-¡kJéâ¨þ¦»ZR¿ Z%t¢³Óª„.èð”Hé�„vP «1xõd:6ŠYðòCƒe*Ïýä�Ð0r‘­Hè\•£¦½i‰¨�TŽªQC§íÙ*‡×¾")ít ³;Ð.NZÚ¢ÍN! –¡¸òUÅÚŸ:…)ԑБÿ�·­r¤ê5ع*G…mµ‰„¾0_Ò!tÎ-‰ 1îNáACRºŽëŽ[åÈСw¾„†Ö;…ý¹´O B»å„ÈM‹f»ÜóÆâ*!ö˜uè�+¡!I¬&„¾7„—\ÈP9JêÒ¡ýzœ�•VÍv!=Ú GBͤO‘×?nKå˜êÐåÒƒsuÄõ&Ív΃ÏZ¸(€àÀJÎù dw 3^þâNaF™;—ÐúTS+G²®–¾ I³]Sk ‰‘ÒÅf;[–_vìØS9_‘b$îÿÄUŽIŶk…Ðn¹þ'3Pgi½ ø»ûu ]ÛΫ§ÈÊQBdÿØéŸìB; eã¤V9ƤC�ÔQ`º«­r¸uµÔyªtNò®­•NaÕ±—×Ft+;›Ð0:Xn&©‹;…)ÝÖ�ú€Y¯¥YÎIr$ôQ[ž[®_OêØChÉæ,¸mp°s­“С ;„Pv}•f»†jG’ 5­×#KÇ…^’ª|ƒZ:¡Bí| •ƒ,�Ë.P9NñÑ¡ý:�Žaµ£TBçH·ë`sJXŒÈU¦<çE-–Ð÷çJh˜Œ]U—÷€N/(rÈÊ"GC �åœä [Bç9CJIè“Öl—!1›zhÀ#UWখ:øD"ÃF„Iè@Ûs–Ü[nqÿ_¥nøÇ^^-:QÞÎ$4´jmðñƒTùŸÐb m˃„Î2‘Z9ÀQ;êHiÅÉ9yeIDAT:ô]FåðЄÐ_ú©Åzh-B»pÉíèÐ÷+(×bÆ/¯BJçŽ Ô¿Íþu¤Ž Š$t†�©;ªZÛÞÚL²ü¶-³J:�uèØ âú�#™ÕøC§P8°ž„n(¥[9¼òJî+kä$g¿˜ÐÆz¯Ù¾ó~š=Ž­�jóY__·K>ßYp CS°bh"¡«Ìhdÿ³:ÁáÀv0Ö¦D½¿j¶Ÿa–±7J¥Æ~œ¥Ê\SQþMvfÄñ'J4w?Dd_š†â®å;Tž[§‡äz+"r::˜ —‘N’ÙkÏ…"r3Úÿzý5XT™XùUiN�OO6.ÐΪ—È d€«J }tÃsºÁ#úut¿4â¤/IsÓ+ò¢ZD^üY,?% ºÀi±ÿ‡þWGÝpU)‹Üø{U*‡;áWDö+¥ê,@-B—¢”È) \EܦÄöÓý<) =dAZXX†ÄõÑétؽ[Ïip…FŽõ"ÕÞ«"RÕÍsžÛO‚ÌPNè[ ÚôÂ8¥sî±ßö‰ýVGBã­+[uªŠÜþ~ê‹RGÝ(=®Af€’¥—¡Ô]KB[äH”*ÉÓä8––JwóÜÍ %¡?�£“†Ê¨Ò§sÎ/IozÿJòÏŽØA|‰†‚aÞèùUÄMG$]Ï\ÃÍèùö÷&àÕÀi¡—#€à{oЧέKäPZ©ì-Q²­%ôçÐîgçôØët CHIëØ±ƒß@/3ð3¥Tð ‘ÿhÛ(ÿ–)¥ÖJÚ_ã–Ò!O½*Ć}νj¬¦– Î›¯^'"O>›:×!ÙwÑk=¯enî2¯c˃2Ýf³Õw3.o¿×î‘ëq0oÚ—wMî*;oJ‡�´Ж”˜�I¥e�y­^-€UzµÁ_/6KsLMœ“Jô¢VJ½´N%"òz?-&�c’•ŒOžq†µ = �ˆE1,ìB:±•£\Øk)š¨/A KÞ%ôrƒ?ˆÈߢ‡³sÊ[œ$™¡¡Kè ê9ò¤qBíÈYÇxhÍ� �sý=àãfÿ_“kÏ«ãÏ�/™rÖÍo/püVà¢H±²Ci«ND‡ªÊtp ¢¬ÖÑ„ÐÁ˜.œ‹=¿N"² Ï1W:{„Ìé”ì•caÓ�Ozåõ›E~ža®å'Bè«ÿ¤”úÛª“Œ+k‘4vÓ�kÊyN‡íÿ3®câ„nâà_"¡‰H•sìNŽ5¡ÓIèu–†ÍªópG\h#‘ü¹vj︈Ð18y'¡Jé!u£âaDÓ(�ÐnR¨RB[8“FÊmr =¤ûçܓȵ�“Q×áÌ6Á#tö5¨CèsB‰¹ÌA# ![‰„®;·.w‚¨„.¼W3ê*!éÄÜF-&¥r@½Žá@B7�ÎÐ@B'PrýJè{e–? t¬Ý™÷+g¸d`a¿ˆLTJow•ã>¡òj;GBo|‚p%_¨PËK1wvùnˆ¹ ^üä—ÄLÃÊ‚Sþ¹¹ÿi“”ÐE„67ïÑ�?L›�¨9ú·œXy)'!¡ï[U°‰é;€ÐW¢]#çÛ¬wœ5Q)u#pcƒ¶m7TFáLؼ³UŽ&ðøl„ž®F_OÎ`ÑÀGÍ&‚Ú„VJ½xw‹m9™ÑDBg«~ì�LéÂcB‰fÅ€ûì™ÀYh+Λ³�N×+¥~\UQÛË›SlÂøtï…êˆLVIè5à«è—æT;r�*ØC÷ >a¶ÿSõ¥Ô p­Ù¶ ¦„?êFÎ,÷’„VJi�Ed=ÂzªÙ£%¦�RuÜÿ-™ì»ÝÑiÚ‘˜" 9xZx,˜mÞÙÏIÛg$âøÿrq†«WqòIEND®B`‚PKê|>]ä¬YÇcchtml/_static/jinja.cssnu„[µü¤/* * jinja.css_t * ~~~~~~~~~~~ * * :copyright: Copyright 2011 by Armin Ronacher. * :license: Flask Design License, see LICENSE for details. */ @import url(http://fonts.googleapis.com/css?family=Crimson+Text); @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: Georgia, serif; font-size: 17px; background-color: white; color: #000; margin: 0; padding: 0; } div.document { width: 940px; margin: 30px auto 0 auto; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 0 0 0 220px; } div.sphinxsidebar { width: 220px; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #ffffff; color: #3E4349; padding: 0 30px 0 30px; } img.floatingflask { padding: 0 0 10px 10px; float: right; } div.footer { width: 940px; margin: 20px auto 30px auto; font-size: 14px; color: #888; text-align: right; } div.footer a { color: #888; } div.related { display: none; } div.sphinxsidebar a { color: #444; text-decoration: none; border-bottom: 1px dotted #999; } div.sphinxsidebar a:hover { border-bottom: 1px solid #999; } div.sphinxsidebar { font-size: 15px; line-height: 1.5; } div.sphinxsidebarwrapper { padding: 18px 10px; } div.sphinxsidebarwrapper p.logo { padding: 0 0 20px 0; margin: 0; text-align: center; } div.sphinxsidebar h3, div.sphinxsidebar h4 { font-family: Georgia, serif; color: #444; font-size: 24px; font-weight: normal; margin: 0 0 5px 0; padding: 0; } div.sphinxsidebar h4 { font-size: 20px; } div.sphinxsidebar h3 a { color: #444; } div.sphinxsidebar p.logo a, div.sphinxsidebar h3 a, div.sphinxsidebar p.logo a:hover, div.sphinxsidebar h3 a:hover { border: none; } div.sphinxsidebar p { color: #555; margin: 10px 0; } div.sphinxsidebar ul { margin: 10px 0; padding: 0; color: #000; } div.sphinxsidebar input { border: 1px solid #ccc; font-family: Georgia, serif; font-size: 14px; } div.sphinxsidebar form.search input[name="q"] { width: 130px; } /* -- body styles ----------------------------------------------------------- */ a { color: #aa0000; text-decoration: underline; } a:hover { color: #dd0000; text-decoration: underline; } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: Crimson Text, Georgia, serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; color: black; } div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: #ddd; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #eaeaea; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { background: #fafafa; margin: 20px -30px; padding: 10px 30px; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } div.admonition tt.xref, div.admonition a tt { border-bottom: 1px solid #fafafa; } dd div.admonition { margin-left: -60px; padding-left: 60px; } div.admonition p.admonition-title { font-family: Georgia, serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight { background-color: white; } dt:target, .highlight { background: #FAF3E8; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.85em; } img.screenshot { } tt.descname, tt.descclassname { font-size: 0.95em; } tt.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #eee; background: #fdfdfd; font-size: 0.9em; } table.footnote + table.footnote { margin-top: -15px; border-top: none; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.footnote td.label { width: 0px; padding: 0.3em 0 0.3em 0.5em; } table.footnote td { padding: 0.3em 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } blockquote { margin: 0 0 0 30px; padding: 0; } ul, ol { margin: 10px 0 10px 30px; padding: 0; } pre { background: #eee; padding: 7px 30px; margin: 15px -30px; line-height: 1.3em; } dl pre, blockquote pre, li pre { margin-left: -60px; padding-left: 60px; } dl dl pre { margin-left: -90px; padding-left: 90px; } tt { background-color: #E8EFF0; color: #222; /* padding: 1px 2px; */ } tt.xref, a tt { background-color: #E8EFF0; border-bottom: 1px solid white; } a.reference { text-decoration: none; border-bottom: 1px dotted #bb0000; } a.reference:hover { border-bottom: 1px solid #dd0000; } a.footnote-reference { text-decoration: none; font-size: 0.7em; vertical-align: top; border-bottom: 1px dotted #bb0000; } a.footnote-reference:hover { border-bottom: 1px solid #dd0000; } a:hover tt { background: #EEE; }PKê|>]�¥ÌØhtml/_static/jquery-3.2.1.jsnu„[µü¤/*! * jQuery JavaScript Library v3.2.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2017-03-20T18:59Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.2.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && Array.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { /* eslint-disable no-unused-vars */ // See https://github.com/eslint/eslint/issues/6125 var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.3 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-08-08 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true && ("form" in elem || "label" in elem); }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && disabledAncestor( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "" + ""; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = ""; return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( el ) { el.innerHTML = ""; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Simple selector that can be filtered directly, removing non-Elements if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } // Complex selector, compare the two sets, removing non-Elements qualifier = jQuery.filter( qualifier, elements ); return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( nodeName( elem, "iframe" ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( jQuery.isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting or other required elements. thead: [ 1, "", "
    " ], col: [ 2, "", "
    " ], tr: [ 2, "", "
    " ], td: [ 3, "", "
    " ], _default: [ 0, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: jQuery.isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var /* eslint-disable max-len */ // See https://github.com/eslint/eslint/issues/3229 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, /* eslint-enable */ // Support: IE <=10 - 11, Edge 12 - 13 // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( ">tbody", elem )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a property mapped along what jQuery.cssProps suggests or to // a vendor prefixed property. function finalPropName( name ) { var ret = jQuery.cssProps[ name ]; if ( !ret ) { ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; } return ret; } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i, val = 0; // If we already have the right measurement, avoid augmentation if ( extra === ( isBorderBox ? "border" : "content" ) ) { i = 4; // Otherwise initialize for horizontal or vertical properties } else { i = name === "width" ? 1 : 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with computed style var valueIsBorderBox, styles = getStyles( elem ), val = curCSS( elem, name, styles ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Fall back to offsetWidth/Height when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) if ( val === "auto" ) { val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnothtmlwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 13 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available, append data to url if ( s.data ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "

    API¶

    This document describes the API to Jinja2 and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Jinja2 templates.

    Basics¶

    Jinja2 uses a central object called the template Environment. Instances of this class are used to store the configuration and global objects, and are used to load templates from the file system or other locations. Even if you are creating templates from strings by using the constructor of Template class, an environment is created automatically for you, albeit a shared one.

    Most applications will create one Environment object on application initialization and use that to load templates. In some cases however, it’s useful to have multiple environments side by side, if different configurations are in use.

    The simplest way to configure Jinja2 to load templates for your application looks roughly like this:

    from jinja2 import Environment, PackageLoader, select_autoescape
    env = Environment(
        loader=PackageLoader('yourapplication', 'templates'),
        autoescape=select_autoescape(['html', 'xml'])
    )
    

    This will create a template environment with the default settings and a loader that looks up the templates in the templates folder inside the yourapplication python package. Different loaders are available and you can also write your own if you want to load templates from a database or other resources. This also enables autoescaping for HTML and XML files.

    To load a template from this environment you just have to call the get_template() method which then returns the loaded Template:

    template = env.get_template('mytemplate.html')
    

    To render it with some variables, just call the render() method:

    print template.render(the='variables', go='here')
    

    Using a template loader rather than passing strings to Template or Environment.from_string() has multiple advantages. Besides being a lot easier to use it also enables template inheritance.

    Notes on Autoescaping

    In future versions of Jinja2 we might enable autoescaping by default for security reasons. As such you are encouraged to explicitly configure autoescaping now instead of relying on the default.

    Unicode¶

    Jinja2 is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters. Additionally newlines are normalized to one end of line sequence which is per default UNIX style (\n).

    Python 2.x supports two ways of representing string objects. One is the str type and the other is the unicode type, both of which extend a type called basestring. Unfortunately the default is str which should not be used to store text based information unless only ASCII characters are used. With Python 2.6 it is possible to make unicode the default on a per module level and with Python 3 it will be the default.

    To explicitly use a Unicode string you have to prefix the string literal with a u: u'Hänsel und Gretel sagen Hallo'. That way Python will store the string as Unicode by decoding the string with the character encoding from the current Python module. If no encoding is specified this defaults to ‘ASCII’ which means that you can’t use any non ASCII identifier.

    To set a better module encoding add the following comment to the first or second line of the Python module using the Unicode literal:

    # -*- coding: utf-8 -*-
    

    We recommend utf-8 as Encoding for Python modules and templates as it’s possible to represent every Unicode character in utf-8 and because it’s backwards compatible to ASCII. For Jinja2 the default encoding of templates is assumed to be utf-8.

    It is not possible to use Jinja2 to process non-Unicode data. The reason for this is that Jinja2 uses Unicode already on the language level. For example Jinja2 treats the non-breaking space as valid whitespace inside expressions which requires knowledge of the encoding or operating on an Unicode string.

    For more details about Unicode in Python have a look at the excellent Unicode documentation.

    Another important thing is how Jinja2 is handling string literals in templates. A naive implementation would be using Unicode strings for all string literals but it turned out in the past that this is problematic as some libraries are typechecking against str explicitly. For example datetime.strftime does not accept Unicode arguments. To not break it completely Jinja2 is returning str for strings that fit into ASCII and for everything else unicode:

    >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
    >>> m.a
    'foo'
    >>> m.b
    u'f\xf6\xf6'
    

    High Level API¶

    The high-level API is the API you will use in the application to load and render Jinja2 templates. The Low Level API on the other side is only useful if you want to dig deeper into Jinja2 or develop extensions.

    class jinja2.Environment([options])¶

    The core component of Jinja is the Environment. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

    Here are the possible initialization parameters:

    block_start_string
    The string marking the beginning of a block. Defaults to '{%'.
    block_end_string
    The string marking the end of a block. Defaults to '%}'.
    variable_start_string
    The string marking the beginning of a print statement. Defaults to '{{'.
    variable_end_string
    The string marking the end of a print statement. Defaults to '}}'.
    comment_start_string
    The string marking the beginning of a comment. Defaults to '{#'.
    comment_end_string
    The string marking the end of a comment. Defaults to '#}'.
    line_statement_prefix
    If given and a string, this will be used as prefix for line based statements. See also Line Statements.
    line_comment_prefix

    If given and a string, this will be used as prefix for line based comments. See also Line Statements.

    New in version 2.2.

    trim_blocks
    If this is set to True the first newline after a block is removed (block, not variable tag!). Defaults to False.
    lstrip_blocks
    If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Defaults to False.
    newline_sequence
    The sequence that starts a newline. Must be one of '\r', '\n' or '\r\n'. The default is '\n' which is a useful default for Linux and OS X systems as well as web applications.
    keep_trailing_newline

    Preserve the trailing newline when rendering templates. The default is False, which causes a single newline, if present, to be stripped from the end of the template.

    New in version 2.7.

    extensions
    List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at the extensions documentation.
    optimized
    should the optimizer be enabled? Default is True.
    undefined
    Undefined or a subclass of it that is used to represent undefined values in the template.
    finalize
    A callable that can be used to process the result of a variable expression before it is output. For example one can convert None implicitly into an empty string here.
    autoescape

    If set to True the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see Markup. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return True or False depending on autoescape should be enabled by default.

    Changed in version 2.4: autoescape can now be a function

    loader
    The template loader for this environment.
    cache_size

    The size of the cache. Per default this is 400 which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to 0 templates are recompiled all the time, if the cache size is -1 the cache will not be cleaned.

    Changed in version 2.8: The cache size was increased to 400 from a low 50.

    auto_reload
    Some loaders load templates from locations where the template sources may change (ie: file system or database). If auto_reload is set to True (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it’s possible to disable that.
    bytecode_cache

    If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don’t have to be parsed if they were not changed.

    See Bytecode Cache for more information.

    enable_async
    If set to true this enables async template execution which allows you to take advantage of newer Python features. This requires Python 3.6 or later.
    shared¶

    If a template was created by using the Template constructor an environment is created automatically. These environments are created as shared environments which means that multiple templates may have the same anonymous environment. For all shared environments this attribute is True, else False.

    sandboxed¶

    If the environment is sandboxed this attribute is True. For the sandbox mode have a look at the documentation for the SandboxedEnvironment.

    filters¶

    A dict of filters for this environment. As long as no template was loaded it’s safe to add new filters or remove old. For custom filters see Custom Filters. For valid filter names have a look at Notes on Identifiers.

    tests¶

    A dict of test functions for this environment. As long as no template was loaded it’s safe to modify this dict. For custom tests see Custom Tests. For valid test names have a look at Notes on Identifiers.

    globals¶

    A dict of global variables. These variables are always available in a template. As long as no template was loaded it’s safe to modify this dict. For more details see The Global Namespace. For valid object names have a look at Notes on Identifiers.

    policies¶

    A dictionary with Policies. These can be reconfigured to change the runtime behavior or certain template features. Usually these are security related.

    code_generator_class¶

    The class used for code generation. This should not be changed in most cases, unless you need to modify the Python code a template compiles to.

    context_class¶

    The context used for templates. This should not be changed in most cases, unless you need to modify internals of how template variables are handled. For details, see Context.

    overlay([options])¶

    Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions.

    Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through.

    undefined([hint, obj, name, exc])¶

    Creates a new Undefined object for name. This is useful for filters or functions that may return undefined objects for some operations. All parameters except of hint should be provided as keyword parameters for better readability. The hint is used as error message for the exception if provided, otherwise the error message will be generated from obj and name automatically. The exception provided as exc is raised if something with the generated undefined object is done that the undefined object does not allow. The default exception is UndefinedError. If a hint is provided the name may be omitted.

    The most common way to create an undefined object is by providing a name only:

    return environment.undefined(name='some_name')
    

    This means that the name some_name is not defined. If the name was from an attribute of an object it makes sense to tell the undefined object the holder object to improve the error message:

    if not hasattr(obj, 'attr'):
        return environment.undefined(obj=obj, name='attr')
    

    For a more complex example you can provide a hint. For example the first() filter creates an undefined object that way:

    return environment.undefined('no first item, sequence was empty')
    

    If it the name or obj is known (for example because an attribute was accessed) it should be passed to the undefined object, even if a custom hint is provided. This gives undefined objects the possibility to enhance the error message.

    add_extension(extension)¶

    Adds an extension after the environment was created.

    New in version 2.5.

    compile_expression(source, undefined_to_none=True)¶

    A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.

    This is useful if applications want to use the same rules as Jinja in template “configuration files� or similar situations.

    Example usage:

    >>> env = Environment()
    >>> expr = env.compile_expression('foo == 42')
    >>> expr(foo=23)
    False
    >>> expr(foo=42)
    True
    

    Per default the return value is converted to None if the expression returns an undefined value. This can be changed by setting undefined_to_none to False.

    >>> env.compile_expression('var')() is None
    True
    >>> env.compile_expression('var', undefined_to_none=False)()
    Undefined
    

    New in version 2.1.

    compile_templates(target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False)¶

    Finds all the templates the loader can find, compiles them and stores them in target. If zip is None, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, zip can be set to 'stored'.

    extensions and filter_func are passed to list_templates(). Each template returned will be compiled to the target folder or zipfile.

    By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set ignore_errors to False and you will get an exception on syntax errors.

    If py_compile is set to True .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don’t give much benefit.

    New in version 2.4.

    extend(**attributes)¶

    Add the items to the instance of the environment if they do not exist yet. This is used by extensions to register callbacks and configuration values without breaking inheritance.

    from_string(source, globals=None, template_class=None)¶

    Load a template from a string. This parses the source given and returns a Template object.

    get_or_select_template(template_name_or_list, parent=None, globals=None)¶

    Does a typecheck and dispatches to select_template() if an iterable of template names is given, otherwise to get_template().

    New in version 2.3.

    get_template(name, parent=None, globals=None)¶

    Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a Template. If the parent parameter is not None, join_path() is called to get the real template name before loading.

    The globals parameter can be used to provide template wide globals. These variables are available in the context at render time.

    If the template does not exist a TemplateNotFound exception is raised.

    Changed in version 2.4: If name is a Template object it is returned from the function unchanged.

    join_path(template, parent)¶

    Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the template parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.

    Subclasses may override this method and implement template path joining here.

    list_templates(extensions=None, filter_func=None)¶

    Returns a list of templates for this environment. This requires that the loader supports the loader’s list_templates() method.

    If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either extensions is set to a list of file extensions for templates, or a filter_func can be provided which is a callable that is passed a template name and should return True if it should end up in the result list.

    If the loader does not support that, a TypeError is raised.

    New in version 2.4.

    select_template(names, parent=None, globals=None)¶

    Works like get_template() but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a TemplatesNotFound exception.

    New in version 2.3.

    Changed in version 2.4: If names contains a Template object it is returned from the function unchanged.

    class jinja2.Template¶

    The central template object. This class represents a compiled template and is used to evaluate it.

    Normally the template object is generated from an Environment but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it’s not possible to specify a loader.

    Every template object has a few methods and members that are guaranteed to exist. However it’s important that a template object should be considered immutable. Modifications on the object are not supported.

    Template objects created from the constructor rather than an environment do have an environment attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings.

    >>> template = Template('Hello {{ name }}!')
    >>> template.render(name='John Doe') == u'Hello John Doe!'
    True
    >>> stream = template.stream(name='John Doe')
    >>> next(stream) == u'Hello John Doe!'
    True
    >>> next(stream)
    Traceback (most recent call last):
        ...
    StopIteration
    
    globals¶

    The dict with the globals of that template. It’s unsafe to modify this dict as it may be shared with other templates or the environment that loaded the template.

    name¶

    The loading name of the template. If the template was loaded from a string this is None.

    filename¶

    The filename of the template on the file system if it was loaded from there. Otherwise this is None.

    render([context])¶

    This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:

    template.render(knights='that say nih')
    template.render({'knights': 'that say nih'})
    

    This will return the rendered template as unicode string.

    generate([context])¶

    For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings.

    It accepts the same arguments as render().

    stream([context])¶

    Works exactly like generate() but returns a TemplateStream.

    render_async([context])¶

    This works similar to render() but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.

    Example usage:

    await template.render_async(knights='that say nih; asynchronously')
    
    generate_async([context])¶

    An async version of generate(). Works very similarly but returns an async iterator instead.

    make_module(vars=None, shared=False, locals=None)¶

    This method works like the module attribute when called without arguments but it will evaluate the template on every call rather than caching it. It’s also possible to provide a dict which is then used as context. The arguments are the same as for the new_context() method.

    module¶

    The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:

    >>> t = Template('{% macro foo() %}42{% endmacro %}23')
    >>> str(t.module)
    '23'
    >>> t.module.foo() == u'42'
    True
    

    This attribute is not available if async mode is enabled.

    class jinja2.environment.TemplateStream¶

    A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded.

    If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration.

    disable_buffering()¶

    Disable the output buffering.

    dump(fp, encoding=None, errors='strict')¶

    Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specify an encoding.

    Example usage:

    Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
    
    enable_buffering(size=5)¶

    Enable buffering. Buffer size items before yielding them.

    Autoescaping¶

    Changed in version 2.4.

    Jinja2 now comes with autoescaping support. As of Jinja 2.9 the autoescape extension is removed and built-in. However autoescaping is not yet enabled by default though this will most likely change in the future. It’s recommended to configure a sensible default for autoescaping. This makes it possible to enable and disable autoescaping on a per-template basis (HTML versus text for instance).

    jinja2.select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False)¶

    Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or for all templates with .html and .xml extensions:

    from jinja2 import Environment, select_autoescape
    env = Environment(autoescape=select_autoescape(
        enabled_extensions=('html', 'xml'),
        default_for_string=True,
    ))
    

    Example configuration to turn it on at all times except if the template ends with .txt:

    from jinja2 import Environment, select_autoescape
    env = Environment(autoescape=select_autoescape(
        disabled_extensions=('txt',),
        default_for_string=True,
        default=True,
    ))
    

    The enabled_extensions is an iterable of all the extensions that autoescaping should be enabled for. Likewise disabled_extensions is a list of all templates it should be disabled for. If a template is loaded from a string then the default from default_for_string is used. If nothing matches then the initial value of autoescaping is set to the value of default.

    For security reasons this function operates case insensitive.

    New in version 2.9.

    Here a recommended setup that enables autoescaping for templates ending in '.html', '.htm' and '.xml' and disabling it by default for all other extensions. You can use the select_autoescape() function for this:

    from jinja2 import Environment, select_autoescape
    env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
                      loader=PackageLoader('mypackage'))
    

    The select_autoescape() function returns a function that works rougly like this:

    def autoescape(template_name):
        if template_name is None:
            return False
        if template_name.endswith(('.html', '.htm', '.xml'))
    

    When implementing a guessing autoescape function, make sure you also accept None as valid template name. This will be passed when generating templates from strings. You should always configure autoescaping as defaults in the future might change.

    Inside the templates the behaviour can be temporarily changed by using the autoescape block (see Autoescape Overrides).

    Notes on Identifiers¶

    Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to match [a-zA-Z_][a-zA-Z0-9_]*. As a matter of fact non ASCII characters are currently not allowed. This limitation will probably go away as soon as unicode identifiers are fully specified for Python 3.

    Filters and tests are looked up in separate namespaces and have slightly modified identifier syntax. Filters and tests may contain dots to group filters and tests by topic. For example it’s perfectly valid to add a function into the filter dict and call it to.unicode. The regular expression for filter and test identifiers is [a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*`.

    Undefined Types¶

    These classes can be used as undefined types. The Environment constructor takes an undefined parameter that can be one of those classes or a custom subclass of Undefined. Whenever the template engine is unable to look up a name or access an attribute one of those objects is created and returned. Some operations on undefined values are then allowed, others fail.

    The closest to regular Python behavior is the StrictUndefined which disallows all operations beside testing if it’s an undefined object.

    class jinja2.Undefined¶

    The default undefined type. This undefined type can be printed and iterated over, but every other access will raise an jinja2.exceptions.UndefinedError:

    >>> foo = Undefined(name='foo')
    >>> str(foo)
    ''
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):
      ...
    jinja2.exceptions.UndefinedError: 'foo' is undefined
    
    _undefined_hint¶

    Either None or an unicode string with the error message for the undefined object.

    _undefined_obj¶

    Either None or the owner object that caused the undefined object to be created (for example because an attribute does not exist).

    _undefined_name¶

    The name for the undefined variable / attribute or just None if no such information exists.

    _undefined_exception¶

    The exception that the undefined object wants to raise. This is usually one of UndefinedError or SecurityError.

    _fail_with_undefined_error(*args, **kwargs)¶

    When called with any arguments this method raises _undefined_exception with an error message generated from the undefined hints stored on the undefined object.

    class jinja2.DebugUndefined¶

    An undefined that returns the debug info when printed.

    >>> foo = DebugUndefined(name='foo')
    >>> str(foo)
    '{{ foo }}'
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):
      ...
    jinja2.exceptions.UndefinedError: 'foo' is undefined
    
    class jinja2.StrictUndefined¶

    An undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it’s defined using the defined test.

    >>> foo = StrictUndefined(name='foo')
    >>> str(foo)
    Traceback (most recent call last):
      ...
    jinja2.exceptions.UndefinedError: 'foo' is undefined
    >>> not foo
    Traceback (most recent call last):
      ...
    jinja2.exceptions.UndefinedError: 'foo' is undefined
    >>> foo + 42
    Traceback (most recent call last):
      ...
    jinja2.exceptions.UndefinedError: 'foo' is undefined
    

    There is also a factory function that can decorate undefined objects to implement logging on failures:

    jinja2.make_logging_undefined(logger=None, base=None)¶

    Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.

    Example:

    logger = logging.getLogger(__name__)
    LoggingUndefined = make_logging_undefined(
        logger=logger,
        base=Undefined
    )
    

    New in version 2.8.

    Parameters:
    • logger – the logger to use. If not provided, a default logger is created.
    • base – the base class to add logging functionality to. This defaults to Undefined.

    Undefined objects are created by calling undefined.

    Implementation

    Undefined objects are implemented by overriding the special __underscore__ methods. For example the default Undefined class implements __unicode__ in a way that it returns an empty string, however __int__ and others still fail with an exception. To allow conversion to int by returning 0 you can implement your own:

    class NullUndefined(Undefined):
        def __int__(self):
            return 0
        def __float__(self):
            return 0.0
    

    To disallow a method, just override it and raise _undefined_exception. Because this is a very common idom in undefined objects there is the helper method _fail_with_undefined_error() that does the error raising automatically. Here a class that works like the regular Undefined but chokes on iteration:

    class NonIterableUndefined(Undefined):
        __iter__ = Undefined._fail_with_undefined_error
    

    The Context¶

    class jinja2.runtime.Context¶

    The template context holds the variables of a template. It stores the values passed to the template and also the names the template exports. Creating instances is neither supported nor useful as it’s created automatically at various stages of the template evaluation and should not be created by hand.

    The context is immutable. Modifications on parent must not happen and modifications on vars are allowed from generated template code only. Template filters and global functions marked as contextfunction()s get the active context passed as first argument and are allowed to access the context read-only.

    The template context supports read only dict operations (get, keys, values, items, iterkeys, itervalues, iteritems, __getitem__, __contains__). Additionally there is a resolve() method that doesn’t fail with a KeyError but returns an Undefined object for missing variables.

    parent¶

    A dict of read only, global variables the template looks up. These can either come from another Context, from the Environment.globals or Template.globals or points to a dict created by combining the globals with the variables passed to the render function. It must not be altered.

    vars¶

    The template local variables. This list contains environment and context functions from the parent scope as well as local modifications and exported variables from the template. The template will modify this dict during template evaluation but filters and context functions are not allowed to modify it.

    environment¶

    The environment that loaded the template.

    exported_vars¶

    This set contains all the names the template exports. The values for the names are in the vars dict. In order to get a copy of the exported variables as dict, get_exported() can be used.

    name¶

    The load name of the template owning this context.

    blocks¶

    A dict with the current mapping of blocks in the template. The keys in this dict are the names of the blocks, and the values a list of blocks registered. The last item in each list is the current active block (latest in the inheritance chain).

    eval_ctx¶

    The current Evaluation Context.

    call(callable, *args, **kwargs)¶

    Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a contextfunction() or environmentfunction().

    get_all()¶

    Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.

    get_exported()¶

    Get a new dict with the exported variables.

    resolve(key)¶

    Looks up a variable like __getitem__ or get but returns an Undefined object with the name of the name looked up.

    Implementation

    Context is immutable for the same reason Python’s frame locals are immutable inside functions. Both Jinja2 and Python are not using the context / frame locals as data storage for variables but only as primary data source.

    When a template accesses a variable the template does not define, Jinja2 looks up the variable in the context, after that the variable is treated as if it was defined in the template.

    Loaders¶

    Loaders are responsible for loading templates from a resource such as the file system. The environment will keep the compiled modules in memory like Python’s sys.modules. Unlike sys.modules however this cache is limited in size by default and templates are automatically reloaded. All loaders are subclasses of BaseLoader. If you want to create your own loader, subclass BaseLoader and override get_source.

    class jinja2.BaseLoader¶

    Baseclass for all loaders. Subclass this and override get_source to implement a custom loading mechanism. The environment provides a get_template method that calls the loader’s load method to get the Template object.

    A very basic example for a loader that looks up templates on the file system could look like this:

    from jinja2 import BaseLoader, TemplateNotFound
    from os.path import join, exists, getmtime
    
    class MyLoader(BaseLoader):
    
        def __init__(self, path):
            self.path = path
    
        def get_source(self, environment, template):
            path = join(self.path, template)
            if not exists(path):
                raise TemplateNotFound(template)
            mtime = getmtime(path)
            with file(path) as f:
                source = f.read().decode('utf-8')
            return source, path, lambda: mtime == getmtime(path)
    
    get_source(environment, template)¶

    Get the template source, filename and reload helper for a template. It’s passed the environment and template name and has to return a tuple in the form (source, filename, uptodate) or raise a TemplateNotFound error if it can’t locate the template.

    The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise None. The filename is used by python for the tracebacks if no loader extension is used.

    The last item in the tuple is the uptodate function. If auto reloading is enabled it’s always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns False the template will be reloaded.

    load(environment, name, globals=None)¶

    Loads a template. This method looks up the template in the cache or loads one by calling get_source(). Subclasses should not override this method as loaders working on collections of other loaders (such as PrefixLoader or ChoiceLoader) will not call this method but get_source directly.

    Here a list of the builtin loaders Jinja2 provides:

    class jinja2.FileSystemLoader(searchpath, encoding='utf-8', followlinks=False)¶

    Loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them.

    The loader takes the path to the templates as string, or if multiple locations are wanted a list of them which is then looked up in the given order:

    >>> loader = FileSystemLoader('/path/to/templates')
    >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
    

    Per default the template encoding is 'utf-8' which can be changed by setting the encoding parameter to something else.

    To follow symbolic links, set the followlinks parameter to True:

    >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)
    

    Changed in version 2.8+: The followlinks parameter was added.

    class jinja2.PackageLoader(package_name, package_path='templates', encoding='utf-8')¶

    Load templates from python eggs or packages. It is constructed with the name of the python package and the path to the templates in that package:

    loader = PackageLoader('mypackage', 'views')
    

    If the package path is not given, 'templates' is assumed.

    Per default the template encoding is 'utf-8' which can be changed by setting the encoding parameter to something else. Due to the nature of eggs it’s only possible to reload templates if the package was loaded from the file system and not a zip file.

    class jinja2.DictLoader(mapping)¶

    Loads a template from a python dict. It’s passed a dict of unicode strings bound to template names. This loader is useful for unittesting:

    >>> loader = DictLoader({'index.html': 'source here'})
    

    Because auto reloading is rarely useful this is disabled per default.

    class jinja2.FunctionLoader(load_func)¶

    A loader that is passed a function which does the loading. The function receives the name of the template and has to return either an unicode string with the template source, a tuple in the form (source, filename, uptodatefunc) or None if the template does not exist.

    >>> def load_template(name):
    ...     if name == 'index.html':
    ...         return '...'
    ...
    >>> loader = FunctionLoader(load_template)
    

    The uptodatefunc is a function that is called if autoreload is enabled and has to return True if the template is still up to date. For more details have a look at BaseLoader.get_source() which has the same return value.

    class jinja2.PrefixLoader(mapping, delimiter='/')¶

    A loader that is passed a dict of loaders where each loader is bound to a prefix. The prefix is delimited from the template by a slash per default, which can be changed by setting the delimiter argument to something else:

    loader = PrefixLoader({
        'app1':     PackageLoader('mypackage.app1'),
        'app2':     PackageLoader('mypackage.app2')
    })
    

    By loading 'app1/index.html' the file from the app1 package is loaded, by loading 'app2/index.html' the file from the second.

    class jinja2.ChoiceLoader(loaders)¶

    This loader works like the PrefixLoader just that no prefix is specified. If a template could not be found by one loader the next one is tried.

    >>> loader = ChoiceLoader([
    ...     FileSystemLoader('/path/to/user/templates'),
    ...     FileSystemLoader('/path/to/system/templates')
    ... ])
    

    This is useful if you want to allow users to override builtin templates from a different location.

    class jinja2.ModuleLoader(path)¶

    This loader loads templates from precompiled templates.

    Example usage:

    >>> loader = ChoiceLoader([
    ...     ModuleLoader('/path/to/compiled/templates'),
    ...     FileSystemLoader('/path/to/templates')
    ... ])
    

    Templates can be precompiled with Environment.compile_templates().

    Bytecode Cache¶

    Jinja 2.1 and higher support external bytecode caching. Bytecode caches make it possible to store the generated bytecode on the file system or a different location to avoid parsing the templates on first use.

    This is especially useful if you have a web application that is initialized on the first request and Jinja compiles many templates at once which slows down the application.

    To use a bytecode cache, instantiate it and pass it to the Environment.

    class jinja2.BytecodeCache¶

    To implement your own bytecode cache you have to subclass this class and override load_bytecode() and dump_bytecode(). Both of these methods are passed a Bucket.

    A very basic bytecode cache that saves the bytecode on the file system:

    from os import path
    
    class MyCache(BytecodeCache):
    
        def __init__(self, directory):
            self.directory = directory
    
        def load_bytecode(self, bucket):
            filename = path.join(self.directory, bucket.key)
            if path.exists(filename):
                with open(filename, 'rb') as f:
                    bucket.load_bytecode(f)
    
        def dump_bytecode(self, bucket):
            filename = path.join(self.directory, bucket.key)
            with open(filename, 'wb') as f:
                bucket.write_bytecode(f)
    

    A more advanced version of a filesystem based bytecode cache is part of Jinja2.

    clear()¶

    Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.

    dump_bytecode(bucket)¶

    Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.

    load_bytecode(bucket)¶

    Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.

    class jinja2.bccache.Bucket(environment, key, checksum)¶

    Buckets are used to store the bytecode for one template. It’s created and initialized by the bytecode cache and passed to the loading functions.

    The buckets get an internal checksum from the cache assigned and use this to automatically reject outdated cache material. Individual bytecode cache subclasses don’t have to care about cache invalidation.

    environment¶

    The Environment that created the bucket.

    key¶

    The unique cache key for this bucket

    code¶

    The bytecode if it’s loaded, otherwise None.

    bytecode_from_string(string)¶

    Load bytecode from a string.

    bytecode_to_string()¶

    Return the bytecode as string.

    load_bytecode(f)¶

    Loads bytecode from a file or file like object.

    reset()¶

    Resets the bucket (unloads the bytecode).

    write_bytecode(f)¶

    Dump the bytecode into the file or file like object passed.

    Builtin bytecode caches:

    class jinja2.FileSystemBytecodeCache(directory=None, pattern='__jinja2_%s.cache')¶

    A bytecode cache that stores bytecode on the filesystem. It accepts two arguments: The directory where the cache items are stored and a pattern string that is used to build the filename.

    If no directory is specified a default cache directory is selected. On Windows the user’s temp directory is used, on UNIX systems a directory is created for the user in the system temp directory.

    The pattern can be used to have multiple separate caches operate on the same directory. The default pattern is '__jinja2_%s.cache'. %s is replaced with the cache key.

    >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
    

    This bytecode cache supports clearing of the cache using the clear method.

    class jinja2.MemcachedBytecodeCache(client, prefix='jinja2/bytecode/', timeout=None, ignore_memcache_errors=True)¶

    This class implements a bytecode cache that uses a memcache cache for storing the information. It does not enforce a specific memcache library (tummy’s memcache or cmemcache) but will accept any class that provides the minimal interface required.

    Libraries compatible with this class:

    (Unfortunately the django cache interface is not compatible because it does not support storing binary data, only unicode. You can however pass the underlying cache client to the bytecode cache which is available as django.core.cache.cache._client.)

    The minimal interface for the client passed to the constructor is this:

    class MinimalClientInterface¶
    set(key, value[, timeout])¶

    Stores the bytecode in the cache. value is a string and timeout the timeout of the key. If timeout is not provided a default timeout or no timeout should be assumed, if it’s provided it’s an integer with the number of seconds the cache item should exist.

    get(key)¶

    Returns the value for the cache key. If the item does not exist in the cache the return value must be None.

    The other arguments to the constructor are the prefix for all keys that is added before the actual cache key and the timeout for the bytecode in the cache system. We recommend a high (or no) timeout.

    This bytecode cache does not support clearing of used items in the cache. The clear method is a no-operation function.

    New in version 2.7: Added support for ignoring memcache errors through the ignore_memcache_errors parameter.

    Async Support¶

    Starting with version 2.9, Jinja2 also supports the Python async and await constructs. As far as template designers go this feature is entirely opaque to them however as a developer you should be aware of how it’s implemented as it influences what type of APIs you can safely expose to the template environment.

    First you need to be aware that by default async support is disabled as enabling it will generate different template code behind the scenes which passes everything through the asyncio event loop. This is important to understand because it has some impact to what you are doing:

    • template rendering will require an event loop to be set for the current thread (asyncio.get_event_loop needs to return one)
    • all template generation code internally runs async generators which means that you will pay a performance penalty even if the non sync methods are used!
    • The sync methods are based on async methods if the async mode is enabled which means that render for instance will internally invoke render_async and run it as part of the current event loop until the execution finished.

    Awaitable objects can be returned from functions in templates and any function call in a template will automatically await the result. This means that you can let provide a method that asynchronously loads data from a database if you so desire and from the template designer’s point of view this is just another function they can call. This means that the await you would normally issue in Python is implied. However this only applies to function calls. If an attribute for instance would be an avaitable object then this would not result in the expected behavior.

    Likewise iterations with a for loop support async iterators.

    Policies¶

    Starting with Jinja 2.9 policies can be configured on the environment which can slightly influence how filters and other template constructs behave. They can be configured with the policies attribute.

    Example:

    env.policies['urlize.rel'] = 'nofollow noopener'
    
    compiler.ascii_str:
    This boolean controls on Python 2 if Jinja2 should store ASCII only literals as bytestring instead of unicode strings. This used to be always enabled for Jinja versions below 2.9 and now can be changed. Traditionally it was done this way since some APIs in Python 2 failed badly for unicode strings (for instance the datetime strftime API). Now however sometimes the inverse is true (for instance str.format). If this is set to False then all strings are stored as unicode internally.
    truncate.leeway:
    Configures the leeway default for the truncate filter. Leeway as introduced in 2.9 but to restore compatibility with older templates it can be configured to 0 to get the old behavior back. The default is 5.
    urlize.rel:
    A string that defines the items for the rel attribute of generated links with the urlize filter. These items are always added. The default is noopener.
    urlize.target:
    The default target that is issued for links from the urlize filter if no other target is defined by the call explicitly.
    json.dumps_function:
    If this is set to a value other than None then the tojson filter will dump with this function instead of the default one. Note that this function should accept arbitrary extra arguments which might be passed in the future from the filter. Currently the only argument that might be passed is indent. The default dump function is json.dumps.
    json.dumps_kwargs:
    Keyword arguments to be passed to the dump function. The default is {'sort_keys': True}.
    ext.i18n.trimmed:
    If this is set to True, {% trans %} blocks of the i18n Extension will always unify linebreaks and surrounding whitespace as if the trimmed modifier was used.

    Utilities¶

    These helper functions and classes are useful if you add custom filters or functions to a Jinja2 environment.

    jinja2.environmentfilter(f)¶

    Decorator for marking environment dependent filters. The current Environment is passed to the filter as first argument.

    jinja2.contextfilter(f)¶

    Decorator for marking context dependent filters. The current Context will be passed as first argument.

    jinja2.evalcontextfilter(f)¶

    Decorator for marking eval-context dependent filters. An eval context object is passed as first argument. For more information about the eval context, see Evaluation Context.

    New in version 2.4.

    jinja2.environmentfunction(f)¶

    This decorator can be used to mark a function or method as environment callable. This decorator works exactly like the contextfunction() decorator just that the first argument is the active Environment and not context.

    jinja2.contextfunction(f)¶

    This decorator can be used to mark a function or method context callable. A context callable is passed the active Context as first argument when called from the template. This is useful if a function wants to get access to the context or functions provided on the context object. For example a function that returns a sorted list of template variables the current template exports could look like this:

    @contextfunction
    def get_exported_names(context):
        return sorted(context.exported_vars)
    
    jinja2.evalcontextfunction(f)¶

    This decorator can be used to mark a function or method as an eval context callable. This is similar to the contextfunction() but instead of passing the context, an evaluation context object is passed. For more information about the eval context, see Evaluation Context.

    New in version 2.4.

    jinja2.escape(s)¶

    Convert the characters &, <, >, ', and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. This function will not escaped objects that do have an HTML representation such as already escaped data.

    The return value is a Markup string.

    jinja2.clear_caches()¶

    Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn’t have to recreate environments and lexers all the time. Normally you don’t have to care about that but if you are measuring memory consumption you may want to clean the caches.

    jinja2.is_undefined(obj)¶

    Check if the object passed is undefined. This does nothing more than performing an instance check against Undefined but looks nicer. This can be used for custom filters or tests that want to react to undefined variables. For example a custom default filter can look like this:

    def default(var, default=''):
        if is_undefined(var):
            return default
        return var
    
    class jinja2.Markup([string])¶

    Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the __html__ interface a couple of frameworks and web applications use. Markup is a direct subclass of unicode and provides all the methods of unicode just that it escapes arguments passed and always returns Markup.

    The escape function returns markup objects so that double escaping can’t happen.

    The constructor of the Markup class can be used for three different things: When passed an unicode object it’s assumed to be safe, when passed an object with an HTML representation (has an __html__ method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe:

    >>> Markup("Hello <em>World</em>!")
    Markup(u'Hello <em>World</em>!')
    >>> class Foo(object):
    ...  def __html__(self):
    ...   return '<a href="#">foo</a>'
    ...
    >>> Markup(Foo())
    Markup(u'<a href="#">foo</a>')
    

    If you want object passed being always treated as unsafe you can use the escape() classmethod to create a Markup object:

    >>> Markup.escape("Hello <em>World</em>!")
    Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')
    

    Operations on a markup string are markup aware which means that all arguments are passed through the escape() function:

    >>> em = Markup("<em>%s</em>")
    >>> em % "foo & bar"
    Markup(u'<em>foo &amp; bar</em>')
    >>> strong = Markup("<strong>%(text)s</strong>")
    >>> strong % {'text': '<blink>hacker here</blink>'}
    Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
    >>> Markup("<em>Hello</em> ") + "<foo>"
    Markup(u'<em>Hello</em> &lt;foo&gt;')
    
    classmethod escape(s)¶

    Escape the string. Works like escape() with the difference that for subclasses of Markup this function would return the correct subclass.

    striptags()¶

    Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one:

    >>> Markup("Main &raquo;  <em>About</em>").striptags()
    u'Main \xbb About'
    
    unescape()¶

    Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities:

    >>> Markup("Main &raquo; <em>About</em>").unescape()
    u'Main \xbb <em>About</em>'
    

    Note

    The Jinja2 Markup class is compatible with at least Pylons and Genshi. It’s expected that more template engines and framework will pick up the __html__ concept soon.

    Exceptions¶

    exception jinja2.TemplateError(message=None)¶

    Baseclass for all template errors.

    exception jinja2.UndefinedError(message=None)¶

    Raised if a template tries to operate on Undefined.

    exception jinja2.TemplateNotFound(name, message=None)¶

    Raised if a template does not exist.

    exception jinja2.TemplatesNotFound(names=(), message=None)¶

    Like TemplateNotFound but raised if multiple templates are selected. This is a subclass of TemplateNotFound exception, so just catching the base exception will catch both.

    New in version 2.2.

    exception jinja2.TemplateSyntaxError(message, lineno, name=None, filename=None)¶

    Raised to tell the user that there is a problem with the template.

    message¶

    The error message as utf-8 bytestring.

    lineno¶

    The line number where the error occurred

    name¶

    The load name for the template as unicode string.

    filename¶

    The filename that loaded the template as bytestring in the encoding of the file system (most likely utf-8 or mbcs on Windows systems).

    The reason why the filename and error message are bytestrings and not unicode strings is that Python 2.x is not using unicode for exceptions and tracebacks as well as the compiler. This will change with Python 3.

    exception jinja2.TemplateRuntimeError(message=None)¶

    A generic runtime error in the template engine. Under some situations Jinja may raise this exception.

    exception jinja2.TemplateAssertionError(message, lineno, name=None, filename=None)¶

    Like a template syntax error, but covers cases where something in the template caused an error at compile time that wasn’t necessarily caused by a syntax error. However it’s a direct subclass of TemplateSyntaxError and has the same attributes.

    Custom Filters¶

    Custom filters are just regular Python functions that take the left side of the filter as first argument and the arguments passed to the filter as extra arguments or keyword arguments.

    For example in the filter {{ 42|myfilter(23) }} the function would be called with myfilter(42, 23). Here for example a simple filter that can be applied to datetime objects to format them:

    def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
        return value.strftime(format)
    

    You can register it on the template environment by updating the filters dict on the environment:

    environment.filters['datetimeformat'] = datetimeformat
    

    Inside the template it can then be used as follows:

    written on: {{ article.pub_date|datetimeformat }}
    publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
    

    Filters can also be passed the current template context or environment. This is useful if a filter wants to return an undefined value or check the current autoescape setting. For this purpose three decorators exist: environmentfilter(), contextfilter() and evalcontextfilter().

    Here a small example filter that breaks a text into HTML line breaks and paragraphs and marks the return value as safe HTML string if autoescaping is enabled:

    import re
    from jinja2 import evalcontextfilter, Markup, escape
    
    _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
    
    @evalcontextfilter
    def nl2br(eval_ctx, value):
        result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
                              for p in _paragraph_re.split(escape(value)))
        if eval_ctx.autoescape:
            result = Markup(result)
        return result
    

    Context filters work the same just that the first argument is the current active Context rather than the environment.

    Evaluation Context¶

    The evaluation context (short eval context or eval ctx) is a new object introduced in Jinja 2.4 that makes it possible to activate and deactivate compiled features at runtime.

    Currently it is only used to enable and disable the automatic escaping but can be used for extensions as well.

    In previous Jinja versions filters and functions were marked as environment callables in order to check for the autoescape status from the environment. In new versions it’s encouraged to check the setting from the evaluation context instead.

    Previous versions:

    @environmentfilter
    def filter(env, value):
        result = do_something(value)
        if env.autoescape:
            result = Markup(result)
        return result
    

    In new versions you can either use a contextfilter() and access the evaluation context from the actual context, or use a evalcontextfilter() which directly passes the evaluation context to the function:

    @contextfilter
    def filter(context, value):
        result = do_something(value)
        if context.eval_ctx.autoescape:
            result = Markup(result)
        return result
    
    @evalcontextfilter
    def filter(eval_ctx, value):
        result = do_something(value)
        if eval_ctx.autoescape:
            result = Markup(result)
        return result
    

    The evaluation context must not be modified at runtime. Modifications must only happen with a nodes.EvalContextModifier and nodes.ScopedEvalContextModifier from an extension, not on the eval context object itself.

    class jinja2.nodes.EvalContext(environment, template_name=None)¶

    Holds evaluation time information. Custom attributes can be attached to it in extensions.

    autoescape¶

    True or False depending on if autoescaping is active or not.

    volatile¶

    True if the compiler cannot evaluate some expressions at compile time. At runtime this should always be False.

    Custom Tests¶

    Tests work like filters just that there is no way for a test to get access to the environment or context and that they can’t be chained. The return value of a test should be True or False. The purpose of a test is to give the template designers the possibility to perform type and conformability checks.

    Here a simple test that checks if a variable is a prime number:

    import math
    
    def is_prime(n):
        if n == 2:
            return True
        for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
            if n % i == 0:
                return False
        return True
    

    You can register it on the template environment by updating the tests dict on the environment:

    environment.tests['prime'] = is_prime
    

    A template designer can then use the test like this:

    {% if 42 is prime %}
        42 is a prime number
    {% else %}
        42 is not a prime number
    {% endif %}
    

    The Global Namespace¶

    Variables stored in the Environment.globals dict are special as they are available for imported templates too, even if they are imported without context. This is the place where you can put variables and functions that should be available all the time. Additionally Template.globals exist that are variables available to a specific template that are available to all render() calls.

    Low Level API¶

    The low level API exposes functionality that can be useful to understand some implementation details, debugging purposes or advanced extension techniques. Unless you know exactly what you are doing we don’t recommend using any of those.

    Environment.lex(source, name=None, filename=None)¶

    Lex the given sourcecode and return a generator that yields tokens as tuples in the form (lineno, token_type, value). This can be useful for extension development and debugging templates.

    This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the preprocess() method.

    Environment.parse(source, name=None, filename=None)¶

    Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates.

    If you are developing Jinja2 extensions this gives you a good overview of the node tree generated.

    Environment.preprocess(source, name=None, filename=None)¶

    Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but not for lex() because there you usually only want the actual source tokenized.

    Template.new_context(vars=None, shared=False, locals=None)¶

    Create a new Context for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to True the data is passed as it to the context without adding the globals.

    locals can be a dict of local variables for internal usage.

    Template.root_render_func(context)¶

    This is the low level render function. It’s passed a Context that has to be created by new_context() of the same template or a compatible template. This render function is generated by the compiler from the template code and returns a generator that yields unicode strings.

    If an exception in the template code happens the template engine will not rewrite the exception but pass through the original one. As a matter of fact this function should only be called from within a render() / generate() / stream() call.

    Template.blocks¶

    A dict of block render functions. Each of these functions works exactly like the root_render_func() with the same limitations.

    Template.is_up_to_date¶

    This attribute is False if there is a newer version of the template available, otherwise True.

    Note

    The low-level API is fragile. Future Jinja2 versions will try not to change it in a backwards incompatible way but modifications in the Jinja2 core may shine through. For example if Jinja2 introduces a new AST node in later versions that may be returned by parse().

    The Meta API¶

    New in version 2.2.

    The meta API returns some information about abstract syntax trees that could help applications to implement more advanced template concepts. All the functions of the meta API operate on an abstract syntax tree as returned by the Environment.parse() method.

    jinja2.meta.find_undeclared_variables(ast)¶

    Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it’s not known which variables will be used depending on the path the execution takes at runtime, all variables are returned.

    >>> from jinja2 import Environment, meta
    >>> env = Environment()
    >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
    >>> meta.find_undeclared_variables(ast) == set(['bar'])
    True
    

    Implementation

    Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a TemplateAssertionError during compilation and as a matter of fact this function can currently raise that exception as well.

    jinja2.meta.find_referenced_templates(ast)¶

    Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, None will be yielded.

    >>> from jinja2 import Environment, meta
    >>> env = Environment()
    >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
    >>> list(meta.find_referenced_templates(ast))
    ['layout.html', None]
    

    This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed.

    PKê|>]ÙÇ‘a…·…·html/changelog.htmlnu„[µü¤ Jinja Changelog — Jinja2 2.10.1 documentation

    Jinja Changelog¶

    Version 2.10.1¶

    Released 2019-04-06

    • SandboxedEnvironment securely handles str.format_map in order to prevent code execution through untrusted format strings. The sandbox already handled str.format.

    Version 2.10¶

    released on November 8th 2017

    • Added a new extension node called OverlayScope which can be used to create an unoptimized scope that will look up all variables from a derived context.
    • Added an in test that works like the in operator. This can be used in combination with reject and select.
    • Added previtem and nextitem to loop contexts, providing access to the previous/next item in the loop. If such an item does not exist, the value is undefined.
    • Added changed(*values) to loop contexts, providing an easy way of checking whether a value has changed since the last iteration (or rather since the last call of the method)
    • Added a namespace function that creates a special object which allows attribute assignment using the set tag. This can be used to carry data across scopes, e.g. from a loop body to code that comes after the loop.
    • Added a trimmed modifier to {% trans %} to strip linebreaks and surrounding whitespace. Also added a new policy to enable this for all trans blocks.
    • The random filter is no longer incorrectly constant folded and will produce a new random choice each time the template is rendered. (#478)
    • Added a unique filter. (#469)
    • Added min and max filters. (#475)
    • Added tests for all comparison operators: eq, ne, lt, le, gt, ge. (#665)
    • import statement cannot end with a trailing comma. (#617, #618)
    • indent filter will not indent blank lines by default. (#685)
    • Add reverse argument for dictsort filter. (#692)
    • Add a NativeEnvironment that renders templates to native Python types instead of strings. (#708)
    • Added filter support to the block set tag. (#489)
    • tojson filter marks output as safe to match documented behavior. (#718)
    • Resolved a bug where getting debug locals for tracebacks could modify template context.
    • Fixed a bug where having many {% elif ... %} blocks resulted in a “too many levels of indentationâ€� error. These blocks now compile to native elif ..: instead of else: if ..: (#759)

    Version 2.9.6¶

    (bugfix release, released on April 3rd 2017)

    • Fixed custom context behavior in fast resolve mode (#675)

    Version 2.9.5¶

    (bugfix release, released on January 28th 2017)

    • Restored the original repr of the internal _GroupTuple because this caused issues with ansible and it was an unintended change. (#654)
    • Added back support for custom contexts that override the old resolve method since it was hard for people to spot that this could cause a regression.
    • Correctly use the buffer for the else block of for loops. This caused invalid syntax errors to be caused on 2.x and completely wrong behavior on Python 3 (#669)
    • Resolve an issue where the {% extends %} tag could not be used with async environments. (#668)
    • Reduce memory footprint slightly by reducing our unicode database dump we use for identifier matching on Python 3 (#666)
    • Fixed autoescaping not working for macros in async compilation mode. (#671)

    Version 2.9.4¶

    (bugfix release, released on January 10th 2017)

    • Solved some warnings for string literals. (#646)
    • Increment the bytecode cache version which was not done due to an oversight before.
    • Corrected bad code generation and scoping for filtered loops. (#649)
    • Resolved an issue where top-level output silencing after known extend blocks could generate invalid code when blocks where contained in if statements. (#651)
    • Made the truncate.leeway default configurable to improve compatibility with older templates.

    Version 2.9.3¶

    (bugfix release, released on January 8th 2017)

    • Restored the use of blocks in macros to the extend that was possible before. On Python 3 it would render a generator repr instead of the block contents. (#645)
    • Set a consistent behavior for assigning of variables in inner scopes when the variable is also read from an outer scope. This now sets the intended behavior in all situations however it does not restore the old behavior where limited assignments to outer scopes was possible. For more information and a discussion see #641
    • Resolved an issue where block scoped would not take advantage of the new scoping rules. In some more exotic cases a variable overriden in a local scope would not make it into a block.
    • Change the code generation of the with statement to be in line with the new scoping rules. This resolves some unlikely bugs in edge cases. This also introduces a new internal With node that can be used by extensions.

    Version 2.9.2¶

    (bugfix release, released on January 8th 2017)

    • Fixed a regression that caused for loops to not be able to use the same variable for the target as well as source iterator. (#640)
    • Add support for a previously unknown behavior of macros. It used to be possible in some circumstances to explicitly provide a caller argument to macros. While badly buggy and unintended it turns out that this is a common case that gets copy pasted around. To not completely break backwards compatibility with the most common cases it’s now possible to provide an explicit keyword argument for caller if it’s given an explicit default. (#642)

    Version 2.9.1¶

    (bugfix release, released on January 7th 2017)

    • Resolved a regression with call block scoping for macros. Nested caller blocks that used the same identifiers as outer macros could refer to the wrong variable incorrectly.

    Version 2.9¶

    (codename Derivation, released on January 7th 2017)

    • Change cache key definition in environment. This fixes a performance regression introduced in 2.8.
    • Added support for generator_stop on supported Python versions (Python 3.5 and later)
    • Corrected a long standing issue with operator precedence of math operations not being what was expected.
    • Added support for Python 3.6 async iterators through a new async mode.
    • Added policies for filter defaults and similar things.
    • urlize now sets “rel noopenerâ€� by default.
    • Support attribute fallback for old-style classes in 2.x.
    • Support toplevel set statements in extend situations.
    • Restored behavior of Cycler for Python 3 users.
    • Subtraction now follows the same behavior as other operators on undefined values.
    • map and friends will now give better error messages if you forgot to quote the parameter.
    • Depend on MarkupSafe 0.23 or higher.
    • Improved the truncate filter to support better truncation in case the string is barely truncated at all.
    • Change the logic for macro autoescaping to be based on the runtime autoescaping information at call time instead of macro define time.
    • Ported a modified version of the tojson filter from Flask to Jinja2 and hooked it up with the new policy framework.
    • Block sets are now marked safe by default.
    • On Python 2 the asciification of ASCII strings can now be disabled with the compiler.ascii_str policy.
    • Tests now no longer accept an arbitrary expression as first argument but a restricted one. This means that you can now properly use multiple tests in one expression without extra parentheses. In particular you can now write foo is divisibleby 2 or foo is divisibleby 3 as you would expect.
    • Greatly changed the scoping system to be more consistent with what template designers and developers expect. There is now no more magic difference between the different include and import constructs. Context is now always propagated the same way. The only remaining differences is the defaults for with context and without context.
    • The with and autoescape tags are now built-in.
    • Added the new select_autoescape function which helps configuring better autoescaping easier.
    • Fixed a runtime error in the sandbox when attributes of async generators were accessed.

    Version 2.8.1¶

    (bugfix release, released on December 29th 2016)

    • Fixed the for_qs flag for urlencode.
    • Fixed regression when applying int to non-string values.
    • SECURITY: if the sandbox mode is used format expressions are now sandboxed with the same rules as in Jinja. This solves various information leakage problems that can occur with format strings.

    Version 2.8¶

    (codename Replacement, released on July 26th 2015)

    • Added target parameter to urlize function.
    • Added support for followsymlinks to the file system loader.
    • The truncate filter now counts the length.
    • Added equalto filter that helps with select filters.
    • Changed cache keys to use absolute file names if available instead of load names.
    • Fixed loop length calculation for some iterators.
    • Changed how Jinja2 enforces strings to be native strings in Python 2 to work when people break their default encoding.
    • Added make_logging_undefined() which returns an undefined object that logs failures into a logger.
    • If unmarshalling of cached data fails the template will be reloaded now.
    • Implemented a block set tag.
    • Default cache size was increased to 400 from a low 50.
    • Fixed is number test to accept long integers in all Python versions.
    • Changed is number to accept Decimal as a number.
    • Added a check for default arguments followed by non-default arguments. This change makes {% macro m(x, y=1, z) %}...{% endmacro %} a syntax error. The previous behavior for this code was broken anyway (resulting in the default value being applied to y).
    • Add ability to use custom subclasses of jinja2.compiler.CodeGenerator and jinja2.runtime.Context by adding two new attributes to the environment (code_generator_class and context_class) (pull request #404).
    • added support for context/environment/evalctx decorator functions on the finalize callback of the environment.
    • escape query strings for urlencode properly. Previously slashes were not escaped in that place.
    • Add ‘base’ parameter to ‘int’ filter.

    Version 2.7.3¶

    (bugfix release, released on June 6th 2014)

    • Security issue: Corrected the security fix for the cache folder. This fix was provided by RedHat.

    Version 2.7.2¶

    (bugfix release, released on January 10th 2014)

    • Prefix loader was not forwarding the locals properly to inner loaders. This is now fixed.
    • Security issue: Changed the default folder for the filesystem cache to be user specific and read and write protected on UNIX systems. See Debian bug 734747 for more information.

    Version 2.7.1¶

    (bugfix release, released on August 7th 2013)

    • Fixed a bug with call_filter not working properly on environment and context filters.
    • Fixed lack of Python 3 support for bytecode caches.
    • Reverted support for defining blocks in included templates as this broke existing templates for users.
    • Fixed some warnings with hashing of undefineds and nodes if Python is run with warnings for Python 3.
    • Added support for properly hashing undefined objects.
    • Fixed a bug with the title filter not working on already uppercase strings.

    Version 2.7¶

    (codename Translation, released on May 20th 2013)

    • Choice and prefix loaders now dispatch source and template lookup separately in order to work in combination with module loaders as advertised.
    • Fixed filesizeformat.
    • Added a non-silent option for babel extraction.
    • Added urlencode filter that automatically quotes values for URL safe usage with utf-8 as only supported encoding. If applications want to change this encoding they can override the filter.
    • Added keep-trailing-newline configuration to environments and templates to optionally preserve the final trailing newline.
    • Accessing last on the loop context no longer causes the iterator to be consumed into a list.
    • Python requirement changed: 2.6, 2.7 or >= 3.3 are required now, supported by same source code, using the “sixâ€� compatibility library.
    • Allow contextfunction and other decorators to be applied to __call__.
    • Added support for changing from newline to different signs in the wordwrap filter.
    • Added support for ignoring memcache errors silently.
    • Added support for keeping the trailing newline in templates.
    • Added finer grained support for stripping whitespace on the left side of blocks.
    • Added map, select, reject, selectattr and rejectattr filters.
    • Added support for loop.depth to figure out how deep inside a recursive loop the code is.
    • Disabled py_compile for pypy and python 3.

    Version 2.6¶

    (codename Convolution, released on July 24th 2011)

    • internal attributes now raise an internal attribute error now instead of returning an undefined. This fixes problems when passing undefined objects to Python semantics expecting APIs.
    • traceback support now works properly for PyPy. (Tested with 1.4)
    • implemented operator intercepting for sandboxed environments. This allows application developers to disable builtin operators for better security. (For instance limit the mathematical operators to actual integers instead of longs)
    • groupby filter now supports dotted notation for grouping by attributes of attributes.
    • scoped blocks now properly treat toplevel assignments and imports. Previously an import suddenly “disappearedâ€� in a scoped block.
    • automatically detect newer Python interpreter versions before loading code from bytecode caches to prevent segfaults on invalid opcodes. The segfault in earlier Jinja2 versions here was not a Jinja2 bug but a limitation in the underlying Python interpreter. If you notice Jinja2 segfaulting in earlier versions after an upgrade of the Python interpreter you don’t have to upgrade, it’s enough to flush the bytecode cache. This just no longer makes this necessary, Jinja2 will automatically detect these cases now.
    • the sum filter can now sum up values by attribute. This is a backwards incompatible change. The argument to the filter previously was the optional starting index which defaults to zero. This now became the second argument to the function because it’s rarely used.
    • like sum, sort now also makes it possible to order items by attribute.
    • like sum and sort, join now also is able to join attributes of objects as string.
    • the internal eval context now has a reference to the environment.
    • added a mapping test to see if an object is a dict or an object with a similar interface.

    Version 2.5.5¶

    (re-release of 2.5.4 with built documentation removed for filesize.
    Released on October 18th 2010)
    • built documentation is no longer part of release.

    Version 2.5.4¶

    (bugfix release, released on October 17th 2010)

    • Fixed extensions not loading properly with overlays.
    • Work around a bug in cpython for the debugger that causes segfaults on 64bit big-endian architectures.

    Version 2.5.3¶

    (bugfix release, released on October 17th 2010)

    • fixed an operator precedence error introduced in 2.5.2. Statements like “-foo.barâ€� had their implicit parentheses applied around the first part of the expression (“(-foo).barâ€�) instead of the more correct “-(foo.bar)â€�.

    Version 2.5.2¶

    (bugfix release, released on August 18th 2010)

    • improved setup.py script to better work with assumptions people might still have from it (--with-speedups).
    • fixed a packaging error that excluded the new debug support.

    Version 2.5.1¶

    (bugfix release, released on August 17th 2010)

    • StopIteration exceptions raised by functions called from templates are now intercepted and converted to undefineds. This solves a lot of debugging grief. (StopIteration is used internally to abort template execution)
    • improved performance of macro calls slightly.
    • babel extraction can now properly extract newstyle gettext calls.
    • using the variable num in newstyle gettext for something else than the pluralize count will no longer raise a KeyError.
    • removed builtin markup class and switched to markupsafe. For backwards compatibility the pure Python implementation still exists but is pulled from markupsafe by the Jinja2 developers. The debug support went into a separate feature called “debugsupportâ€� and is disabled by default because it is only relevant for Python 2.4
    • fixed an issue with unary operators having the wrong precedence.

    Version 2.5¶

    (codename Incoherence, released on May 29th 2010)

    • improved the sort filter (should have worked like this for a long time) by adding support for case insensitive searches.
    • fixed a bug for getattribute constant folding.
    • support for newstyle gettext translations which result in a nicer in-template user interface and more consistent catalogs. (Whitespace Trimming)
    • it’s now possible to register extensions after an environment was created.

    Version 2.4.1¶

    (bugfix release, released on April 20th 2010)

    • fixed an error reporting bug for undefineds.

    Version 2.4¶

    (codename Correlation, released on April 13th 2010)

    • the environment template loading functions now transparently pass through a template object if it was passed to it. This makes it possible to import or extend from a template object that was passed to the template.
    • added a ModuleLoader that can load templates from precompiled sources. The environment now features a method to compile the templates from a configured loader into a zip file or folder.
    • the _speedups C extension now supports Python 3.
    • added support for autoescaping toggling sections and support for evaluation contexts (Evaluation Context).
    • extensions have a priority now.

    Version 2.3.1¶

    (bugfix release, released on February 19th 2010)

    • fixed an error reporting bug on all python versions
    • fixed an error reporting bug on Python 2.4

    Version 2.3¶

    (codename 3000 Pythons, released on February 10th 2010)

    • fixes issue with code generator that causes unbound variables to be generated if set was used in if-blocks and other small identifier problems.
    • include tags are now able to select between multiple templates and take the first that exists, if a list of templates is given.
    • fixed a problem with having call blocks in outer scopes that have an argument that is also used as local variable in an inner frame (#360).
    • greatly improved error message reporting (#339)
    • implicit tuple expressions can no longer be totally empty. This change makes {% if %}...{% endif %} a syntax error now. (#364)
    • added support for translator comments if extracted via babel.
    • added with-statement extension.
    • experimental Python 3 support.

    Version 2.2.1¶

    (bugfix release, released on September 14th 2009)

    • fixes some smaller problems for Jinja2 on Jython.

    Version 2.2¶

    (codename Kong, released on September 13th 2009)

    • Include statements can now be marked with ignore missing to skip non existing templates.
    • Priority of not raised. It’s now possible to write not foo in bar as an alias to foo not in bar like in python. Previously the grammar required parentheses (not (foo in bar)) which was odd.
    • Fixed a bug that caused syntax errors when defining macros or using the {% call %} tag inside loops.
    • Fixed a bug in the parser that made {{ foo[1, 2] }} impossible.
    • Made it possible to refer to names from outer scopes in included templates that were unused in the callers frame (#327)
    • Fixed a bug that caused internal errors if names where used as iteration variable and regular variable after the loop if that variable was unused before the loop. (#331)
    • Added support for optional scoped modifier to blocks.
    • Added support for line-comments.
    • Added the meta module.
    • Renamed (undocumented) attribute “overlayâ€� to “overlayedâ€� on the environment because it was clashing with a method of the same name.
    • speedup extension is now disabled by default.

    Version 2.1.1¶

    (bugfix release, released on December 25th 2008)

    • Fixed a translation error caused by looping over empty recursive loops.

    Version 2.1¶

    (codename Yasuz�, released on November 23rd 2008)

    • fixed a bug with nested loops and the special loop variable. Before the change an inner loop overwrote the loop variable from the outer one after iteration.
    • fixed a bug with the i18n extension that caused the explicit pluralization block to look up the wrong variable.
    • fixed a limitation in the lexer that made {{ foo.0.0 }} impossible.
    • index based subscribing of variables with a constant value returns an undefined object now instead of raising an index error. This was a bug caused by eager optimizing.
    • the i18n extension looks up foo.ugettext now followed by foo.gettext if an translations object is installed. This makes dealing with custom translations classes easier.
    • fixed a confusing behavior with conditional extending. loops were partially executed under some conditions even though they were not part of a visible area.
    • added sort filter that works like dictsort but for arbitrary sequences.
    • fixed a bug with empty statements in macros.
    • implemented a bytecode cache system. (Bytecode Cache)
    • the template context is now weakref-able
    • inclusions and imports “with contextâ€� forward all variables now, not only the initial context.
    • added a cycle helper called cycler.
    • added a joining helper called joiner.
    • added a compile_expression method to the environment that allows compiling of Jinja expressions into callable Python objects.
    • fixed an escaping bug in urlize

    Version 2.0¶

    (codename jinjavitus, released on July 17th 2008)

    • the subscribing of objects (looking up attributes and items) changed from slightly. It’s now possible to give attributes or items a higher priority by either using dot-notation lookup or the bracket syntax. This also changed the AST slightly. Subscript is gone and was replaced with Getitem and Getattr.

      For more information see the implementation details.

    • added support for preprocessing and token stream filtering for extensions. This would allow extensions to allow simplified gettext calls in template data and something similar.

    • added jinja2.environment.TemplateStream.dump().

    • added missing support for implicit string literal concatenation. {{ "foo" "bar" }} is equivalent to {{ "foobar" }}

    • else is optional for conditional expressions. If not given it evaluates to false.

    • improved error reporting for undefined values by providing a position.

    • filesizeformat filter uses decimal prefixes now per default and can be set to binary mode with the second parameter.

    • fixed bug in finalizer

    Version 2.0rc1¶

    (no codename, released on June 9th 2008)

    • first release of Jinja2
    PKê|>]'1xŠÇõÇõhtml/extensions.htmlnu„[µü¤ Extensions — Jinja2 2.10.1 documentation

    Extensions¶

    Jinja2 supports extensions that can add extra filters, tests, globals or even extend the parser. The main motivation of extensions is to move often used code into a reusable class like adding support for internationalization.

    Adding Extensions¶

    Extensions are added to the Jinja2 environment at creation time. Once the environment is created additional extensions cannot be added. To add an extension pass a list of extension classes or import paths to the extensions parameter of the Environment constructor. The following example creates a Jinja2 environment with the i18n extension loaded:

    jinja_env = Environment(extensions=['jinja2.ext.i18n'])
    

    i18n Extension¶

    Import name: jinja2.ext.i18n

    The i18n extension can be used in combination with gettext or babel. If the i18n extension is enabled Jinja2 provides a trans statement that marks the wrapped string as translatable and calls gettext.

    After enabling, dummy _ function that forwards calls to gettext is added to the environment globals. An internationalized application then has to provide a gettext function and optionally an ngettext function into the namespace, either globally or for each rendering.

    Environment Methods¶

    After enabling the extension, the environment provides the following additional methods:

    jinja2.Environment.install_gettext_translations(translations, newstyle=False)¶

    Installs a translation globally for that environment. The translations object provided must implement at least ugettext and ungettext. The gettext.NullTranslations and gettext.GNUTranslations classes as well as Babels Translations class are supported.

    Changed in version 2.5: newstyle gettext added

    jinja2.Environment.install_null_translations(newstyle=False)¶

    Install dummy gettext functions. This is useful if you want to prepare the application for internationalization but don’t want to implement the full internationalization system yet.

    Changed in version 2.5: newstyle gettext added

    jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)¶

    Installs the given gettext and ngettext callables into the environment as globals. They are supposed to behave exactly like the standard library’s gettext.ugettext() and gettext.ungettext() functions.

    If newstyle is activated, the callables are wrapped to work like newstyle callables. See Whitespace Trimming for more information.

    New in version 2.5.

    jinja2.Environment.uninstall_gettext_translations()¶

    Uninstall the translations again.

    jinja2.Environment.extract_translations(source)¶

    Extract localizable strings from the given template node or source.

    For every string found this function yields a (lineno, function, message) tuple, where:

    • lineno is the number of the line on which the string was found,
    • function is the name of the gettext function used (if the string was extracted from embedded Python code), and
    • message is the string itself (a unicode object, or a tuple of unicode objects for functions with multiple string arguments).

    If Babel is installed, the babel integration can be used to extract strings for babel.

    For a web application that is available in multiple languages but gives all the users the same language (for example a multilingual forum software installed for a French community) may load the translations once and add the translation methods to the environment at environment generation time:

    translations = get_gettext_translations()
    env = Environment(extensions=['jinja2.ext.i18n'])
    env.install_gettext_translations(translations)
    

    The get_gettext_translations function would return the translator for the current configuration. (For example by using gettext.find)

    The usage of the i18n extension for template designers is covered as part of the template documentation.

    Whitespace Trimming¶

    New in version 2.10.

    Linebreaks and surrounding whitespace can be automatically trimmed by enabling the ext.i18n.trimmed policy.

    Newstyle Gettext¶

    New in version 2.5.

    Starting with version 2.5 you can use newstyle gettext calls. These are inspired by trac’s internal gettext functions and are fully supported by the babel extraction tool. They might not work as expected by other extraction tools in case you are not using Babel’s.

    What’s the big difference between standard and newstyle gettext calls? In general they are less to type and less error prone. Also if they are used in an autoescaping environment they better support automatic escaping. Here are some common differences between old and new calls:

    standard gettext:

    {{ gettext('Hello World!') }}
    {{ gettext('Hello %(name)s!')|format(name='World') }}
    {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
        num=apples|count
    )}}
    

    newstyle gettext looks like this instead:

    {{ gettext('Hello World!') }}
    {{ gettext('Hello %(name)s!', name='World') }}
    {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
    

    The advantages of newstyle gettext are that you have less to type and that named placeholders become mandatory. The latter sounds like a disadvantage but solves a lot of troubles translators are often facing when they are unable to switch the positions of two placeholder. With newstyle gettext, all format strings look the same.

    Furthermore with newstyle gettext, string formatting is also used if no placeholders are used which makes all strings behave exactly the same. Last but not least are newstyle gettext calls able to properly mark strings for autoescaping which solves lots of escaping related issues many templates are experiencing over time when using autoescaping.

    Expression Statement¶

    Import name: jinja2.ext.do

    The “do� aka expression-statement extension adds a simple do tag to the template engine that works like a variable expression but ignores the return value.

    Loop Controls¶

    Import name: jinja2.ext.loopcontrols

    This extension adds support for break and continue in loops. After enabling, Jinja2 provides those two keywords which work exactly like in Python.

    With Statement¶

    Import name: jinja2.ext.with_

    Changed in version 2.9.

    This extension is now built-in and no longer does anything.

    Autoescape Extension¶

    Import name: jinja2.ext.autoescape

    Changed in version 2.9.

    This extension was removed and is now built-in. Enabling the extension no longer does anything.

    Writing Extensions¶

    By writing extensions you can add custom tags to Jinja2. This is a non-trivial task and usually not needed as the default tags and expressions cover all common use cases. The i18n extension is a good example of why extensions are useful. Another one would be fragment caching.

    When writing extensions you have to keep in mind that you are working with the Jinja2 template compiler which does not validate the node tree you are passing to it. If the AST is malformed you will get all kinds of compiler or runtime errors that are horrible to debug. Always make sure you are using the nodes you create correctly. The API documentation below shows which nodes exist and how to use them.

    Example Extension¶

    The following example implements a cache tag for Jinja2 by using the Werkzeug caching contrib module:

    from jinja2 import nodes
    from jinja2.ext import Extension
    
    
    class FragmentCacheExtension(Extension):
        # a set of names that trigger the extension.
        tags = set(['cache'])
    
        def __init__(self, environment):
            super(FragmentCacheExtension, self).__init__(environment)
    
            # add the defaults to the environment
            environment.extend(
                fragment_cache_prefix='',
                fragment_cache=None
            )
    
        def parse(self, parser):
            # the first token is the token that started the tag.  In our case
            # we only listen to ``'cache'`` so this will be a name token with
            # `cache` as value.  We get the line number so that we can give
            # that line number to the nodes we create by hand.
            lineno = next(parser.stream).lineno
    
            # now we parse a single expression that is used as cache key.
            args = [parser.parse_expression()]
    
            # if there is a comma, the user provided a timeout.  If not use
            # None as second parameter.
            if parser.stream.skip_if('comma'):
                args.append(parser.parse_expression())
            else:
                args.append(nodes.Const(None))
    
            # now we parse the body of the cache block up to `endcache` and
            # drop the needle (which would always be `endcache` in that case)
            body = parser.parse_statements(['name:endcache'], drop_needle=True)
    
            # now return a `CallBlock` node that calls our _cache_support
            # helper method on this extension.
            return nodes.CallBlock(self.call_method('_cache_support', args),
                                   [], [], body).set_lineno(lineno)
    
        def _cache_support(self, name, timeout, caller):
            """Helper callback."""
            key = self.environment.fragment_cache_prefix + name
    
            # try to load the block from the cache
            # if there is no fragment in the cache, render it and store
            # it in the cache.
            rv = self.environment.fragment_cache.get(key)
            if rv is not None:
                return rv
            rv = caller()
            self.environment.fragment_cache.add(key, rv, timeout)
            return rv
    

    And here is how you use it in an environment:

    from jinja2 import Environment
    from werkzeug.contrib.cache import SimpleCache
    
    env = Environment(extensions=[FragmentCacheExtension])
    env.fragment_cache = SimpleCache()
    

    Inside the template it’s then possible to mark blocks as cacheable. The following example caches a sidebar for 300 seconds:

    {% cache 'sidebar', 300 %}
    <div class="sidebar">
        ...
    </div>
    {% endcache %}
    

    Extension API¶

    Extensions always have to extend the jinja2.ext.Extension class:

    class jinja2.ext.Extension(environment)¶

    Extensions can be used to add extra functionality to the Jinja template system at the parser level. Custom extensions are bound to an environment but may not store environment specific data on self. The reason for this is that an extension can be bound to another environment (for overlays) by creating a copy and reassigning the environment attribute.

    As extensions are created by the environment they cannot accept any arguments for configuration. One may want to work around that by using a factory function, but that is not possible as extensions are identified by their import name. The correct way to configure the extension is storing the configuration values on the environment. Because this way the environment ends up acting as central configuration storage the attributes may clash which is why extensions have to ensure that the names they choose for configuration are not too generic. prefix for example is a terrible name, fragment_cache_prefix on the other hand is a good name as includes the name of the extension (fragment cache).

    identifier¶

    The identifier of the extension. This is always the true import name of the extension class and must not be changed.

    tags¶

    If the extension implements custom tags this is a set of tag names the extension is listening for.

    attr(name, lineno=None)¶

    Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code.

    self.attr('_my_attribute', lineno=lineno)
    
    call_method(name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None)¶

    Call a method of the extension. This is a shortcut for attr() + jinja2.nodes.Call.

    filter_stream(stream)¶

    It’s passed a TokenStream that can be used to filter tokens returned. This method has to return an iterable of Tokens, but it doesn’t have to return a TokenStream.

    In the ext folder of the Jinja2 source distribution there is a file called inlinegettext.py which implements a filter that utilizes this method.

    parse(parser)¶

    If any of the tags matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.

    preprocess(source, name, filename=None)¶

    This method is called before the actual lexing and can be used to preprocess the source. The filename is optional. The return value must be the preprocessed source.

    Parser API¶

    The parser passed to Extension.parse() provides ways to parse expressions of different types. The following methods may be used by extensions:

    class jinja2.parser.Parser(environment, source, name=None, filename=None, state=None)¶

    This is the central parsing class Jinja2 uses. It’s passed to extensions and can be used to parse expressions or statements.

    filename¶

    The filename of the template the parser processes. This is not the load name of the template. For the load name see name. For templates that were not loaded form the file system this is None.

    name¶

    The load name of the template.

    stream¶

    The current TokenStream

    fail(msg, lineno=None, exc=<class 'jinja2.exceptions.TemplateSyntaxError'>)¶

    Convenience method that raises exc with the message, passed line number or last line number as well as the current name and filename.

    free_identifier(lineno=None)¶

    Return a new free identifier as InternalName.

    parse_assign_target(with_tuple=True, name_only=False, extra_end_rules=None, with_namespace=False)¶

    Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting with_tuple to False. If only assignments to names are wanted name_only can be set to True. The extra_end_rules parameter is forwarded to the tuple parsing function. If with_namespace is enabled, a namespace assignment may be parsed.

    parse_expression(with_condexpr=True)¶

    Parse an expression. Per default all expressions are parsed, if the optional with_condexpr parameter is set to False conditional expressions are not parsed.

    parse_statements(end_tokens, drop_needle=False)¶

    Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the end_tokens is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted drop_needle can be set to True and the end token is removed.

    parse_tuple(simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False)¶

    Works like parse_expression but if multiple expressions are delimited by a comma a Tuple node is created. This method could also return a regular expression instead of a tuple if no commas where found.

    The default parsing mode is a full tuple. If simplified is True only names and literals are parsed. The no_condexpr parameter is forwarded to parse_expression().

    Because tuples do not require delimiters and may end in a bogus comma an extra hint is needed that marks the end of a tuple. For example for loops support tuples between for and in. In that case the extra_end_rules is set to ['name:in'].

    explicit_parentheses is true if the parsing was triggered by an expression in parentheses. This is used to figure out if an empty tuple is a valid expression or not.

    class jinja2.lexer.TokenStream(generator, name, filename)¶

    A token stream is an iterable that yields Tokens. The parser however does not iterate over it but calls next() to go one token ahead. The current active token is stored as current.

    current¶

    The current Token.

    __next__()¶

    Go one token ahead and return the old one.

    Use the built-in next() instead of calling this directly.

    eos¶

    Are we at the end of the stream?

    expect(expr)¶

    Expect a given token type and return it. This accepts the same argument as jinja2.lexer.Token.test().

    look()¶

    Look at the next token.

    next_if(expr)¶

    Perform the token test and return the token if it matched. Otherwise the return value is None.

    push(token)¶

    Push a token back to the stream.

    skip(n=1)¶

    Got n tokens ahead.

    skip_if(expr)¶

    Like next_if() but only returns True or False.

    class jinja2.lexer.Token¶

    Token class.

    lineno¶

    The line number of the token

    type¶

    The type of the token. This string is interned so you may compare it with arbitrary strings using the is operator.

    value¶

    The value of the token.

    test(expr)¶

    Test a token against a token expression. This can either be a token type or 'token_type:token_value'. This can only test against string values and types.

    test_any(*iterable)¶

    Test against multiple token expressions.

    There is also a utility function in the lexer module that can count newline characters in strings:

    jinja2.lexer.count_newlines(value)¶

    Count the number of newline characters in the string. This is useful for extensions that filter a stream.

    AST¶

    The AST (Abstract Syntax Tree) is used to represent a template after parsing. It’s build of nodes that the compiler then converts into executable Python code objects. Extensions that provide custom statements can return nodes to execute custom Python code.

    The list below describes all nodes that are currently available. The AST may change between Jinja2 versions but will stay backwards compatible.

    For more information have a look at the repr of jinja2.Environment.parse().

    class jinja2.nodes.Node¶

    Baseclass for all Jinja2 nodes. There are a number of nodes available of different types. There are four major types:

    All nodes have fields and attributes. Fields may be other nodes, lists, or arbitrary values. Fields are passed to the constructor as regular positional arguments, attributes as keyword arguments. Each node has two attributes: lineno (the line number of the node) and environment. The environment attribute is set at the end of the parsing process for all nodes automatically.

    find(node_type)¶

    Find the first node of a given type. If no such node exists the return value is None.

    find_all(node_type)¶

    Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.

    iter_child_nodes(exclude=None, only=None)¶

    Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned.

    iter_fields(exclude=None, only=None)¶

    This method iterates over all fields that are defined and yields (key, value) tuples. Per default all fields are returned, but it’s possible to limit that to some fields by providing the only parameter or to exclude some using the exclude parameter. Both should be sets or tuples of field names.

    set_ctx(ctx)¶

    Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a ‘load’ context as it’s the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.

    set_environment(environment)¶

    Set the environment for all nodes.

    set_lineno(lineno, override=False)¶

    Set the line numbers of the node and children.

    class jinja2.nodes.Expr¶

    Baseclass for all expressions.

    Node type:Node
    as_const(eval_ctx=None)¶

    Return the value of the expression as constant or raise Impossible if this was not possible.

    An EvalContext can be provided, if none is given a default context is created which requires the nodes to have an attached environment.

    Changed in version 2.4: the eval_ctx parameter was added.

    can_assign()¶

    Check if it’s possible to assign something to this node.

    class jinja2.nodes.BinExpr(left, right)¶

    Baseclass for all binary expressions.

    Node type:Expr
    class jinja2.nodes.Add(left, right)¶

    Add the left to the right node.

    Node type:BinExpr
    class jinja2.nodes.And(left, right)¶

    Short circuited AND.

    Node type:BinExpr
    class jinja2.nodes.Div(left, right)¶

    Divides the left by the right node.

    Node type:BinExpr
    class jinja2.nodes.FloorDiv(left, right)¶

    Divides the left by the right node and truncates conver the result into an integer by truncating.

    Node type:BinExpr
    class jinja2.nodes.Mod(left, right)¶

    Left modulo right.

    Node type:BinExpr
    class jinja2.nodes.Mul(left, right)¶

    Multiplies the left with the right node.

    Node type:BinExpr
    class jinja2.nodes.Or(left, right)¶

    Short circuited OR.

    Node type:BinExpr
    class jinja2.nodes.Pow(left, right)¶

    Left to the power of right.

    Node type:BinExpr
    class jinja2.nodes.Sub(left, right)¶

    Subtract the right from the left node.

    Node type:BinExpr
    class jinja2.nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs)¶

    Calls an expression. args is a list of arguments, kwargs a list of keyword arguments (list of Keyword nodes), and dyn_args and dyn_kwargs has to be either None or a node that is used as node for dynamic positional (*args) or keyword (**kwargs) arguments.

    Node type:Expr
    class jinja2.nodes.Compare(expr, ops)¶

    Compares an expression with some other expressions. ops must be a list of Operands.

    Node type:Expr
    class jinja2.nodes.Concat(nodes)¶

    Concatenates the list of expressions provided after converting them to unicode.

    Node type:Expr
    class jinja2.nodes.CondExpr(test, expr1, expr2)¶

    A conditional expression (inline if expression). ({{ foo if bar else baz }})

    Node type:Expr
    class jinja2.nodes.ContextReference¶

    Returns the current template context. It can be used like a Name node, with a 'load' ctx and will return the current Context object.

    Here an example that assigns the current template name to a variable named foo:

    Assign(Name('foo', ctx='store'),
           Getattr(ContextReference(), 'name'))
    
    Node type:Expr
    class jinja2.nodes.EnvironmentAttribute(name)¶

    Loads an attribute from the environment object. This is useful for extensions that want to call a callback stored on the environment.

    Node type:Expr
    class jinja2.nodes.ExtensionAttribute(identifier, name)¶

    Returns the attribute of an extension bound to the environment. The identifier is the identifier of the Extension.

    This node is usually constructed by calling the attr() method on an extension.

    Node type:Expr
    class jinja2.nodes.Filter(node, name, args, kwargs, dyn_args, dyn_kwargs)¶

    This node applies a filter on an expression. name is the name of the filter, the rest of the fields are the same as for Call.

    If the node of a filter is None the contents of the last buffer are filtered. Buffers are created by macros and filter blocks.

    Node type:Expr
    class jinja2.nodes.Getattr(node, attr, ctx)¶

    Get an attribute or item from an expression that is a ascii-only bytestring and prefer the attribute.

    Node type:Expr
    class jinja2.nodes.Getitem(node, arg, ctx)¶

    Get an attribute or item from an expression and prefer the item.

    Node type:Expr
    class jinja2.nodes.ImportedName(importname)¶

    If created with an import name the import name is returned on node access. For example ImportedName('cgi.escape') returns the escape function from the cgi module on evaluation. Imports are optimized by the compiler so there is no need to assign them to local variables.

    Node type:Expr
    class jinja2.nodes.InternalName(name)¶

    An internal name in the compiler. You cannot create these nodes yourself but the parser provides a free_identifier() method that creates a new identifier for you. This identifier is not available from the template and is not threated specially by the compiler.

    Node type:Expr
    class jinja2.nodes.Literal¶

    Baseclass for literals.

    Node type:Expr
    class jinja2.nodes.Const(value)¶

    All constant values. The parser will return this node for simple constants such as 42 or "foo" but it can be used to store more complex values such as lists too. Only constants with a safe representation (objects where eval(repr(x)) == x is true).

    Node type:Literal
    class jinja2.nodes.Dict(items)¶

    Any dict literal such as {1: 2, 3: 4}. The items must be a list of Pair nodes.

    Node type:Literal
    class jinja2.nodes.List(items)¶

    Any list literal such as [1, 2, 3]

    Node type:Literal
    class jinja2.nodes.TemplateData(data)¶

    A constant template string.

    Node type:Literal
    class jinja2.nodes.Tuple(items, ctx)¶

    For loop unpacking and some other things like multiple arguments for subscripts. Like for Name ctx specifies if the tuple is used for loading the names or storing.

    Node type:Literal
    class jinja2.nodes.MarkSafe(expr)¶

    Mark the wrapped expression as safe (wrap it as Markup).

    Node type:Expr
    class jinja2.nodes.MarkSafeIfAutoescape(expr)¶

    Mark the wrapped expression as safe (wrap it as Markup) but only if autoescaping is active.

    New in version 2.5.

    Node type:Expr
    class jinja2.nodes.Name(name, ctx)¶

    Looks up a name or stores a value in a name. The ctx of the node can be one of the following values:

    • store: store a value in the name
    • load: load that name
    • param: like store but if the name was defined as function parameter.
    Node type:Expr
    class jinja2.nodes.NSRef(name, attr)¶

    Reference to a namespace value assignment

    Node type:Expr
    class jinja2.nodes.Slice(start, stop, step)¶

    Represents a slice object. This must only be used as argument for Subscript.

    Node type:Expr
    class jinja2.nodes.Test(node, name, args, kwargs, dyn_args, dyn_kwargs)¶

    Applies a test on an expression. name is the name of the test, the rest of the fields are the same as for Call.

    Node type:Expr
    class jinja2.nodes.UnaryExpr(node)¶

    Baseclass for all unary expressions.

    Node type:Expr
    class jinja2.nodes.Neg(node)¶

    Make the expression negative.

    Node type:UnaryExpr
    class jinja2.nodes.Not(node)¶

    Negate the expression.

    Node type:UnaryExpr
    class jinja2.nodes.Pos(node)¶

    Make the expression positive (noop for most expressions)

    Node type:UnaryExpr
    class jinja2.nodes.Helper¶

    Nodes that exist in a specific context only.

    Node type:Node
    class jinja2.nodes.Keyword(key, value)¶

    A key, value pair for keyword arguments where key is a string.

    Node type:Helper
    class jinja2.nodes.Operand(op, expr)¶

    Holds an operator and an expression. The following operators are available: %, **, *, +, -, //, /, eq, gt, gteq, in, lt, lteq, ne, not, notin

    Node type:Helper
    class jinja2.nodes.Pair(key, value)¶

    A key, value pair for dicts.

    Node type:Helper
    class jinja2.nodes.Stmt¶

    Base node for all statements.

    Node type:Node
    class jinja2.nodes.Assign(target, node)¶

    Assigns an expression to a target.

    Node type:Stmt
    class jinja2.nodes.AssignBlock(target, filter, body)¶

    Assigns a block to a target.

    Node type:Stmt
    class jinja2.nodes.Block(name, body, scoped)¶

    A node that represents a block.

    Node type:Stmt
    class jinja2.nodes.Break¶

    Break a loop.

    Node type:Stmt
    class jinja2.nodes.CallBlock(call, args, defaults, body)¶

    Like a macro without a name but a call instead. call is called with the unnamed macro as caller argument this node holds.

    Node type:Stmt
    class jinja2.nodes.Continue¶

    Continue a loop.

    Node type:Stmt
    class jinja2.nodes.EvalContextModifier(options)¶

    Modifies the eval context. For each option that should be modified, a Keyword has to be added to the options list.

    Example to change the autoescape setting:

    EvalContextModifier(options=[Keyword('autoescape', Const(True))])
    
    Node type:Stmt
    class jinja2.nodes.ScopedEvalContextModifier(options, body)¶

    Modifies the eval context and reverts it later. Works exactly like EvalContextModifier but will only modify the EvalContext for nodes in the body.

    Node type:EvalContextModifier
    class jinja2.nodes.ExprStmt(node)¶

    A statement that evaluates an expression and discards the result.

    Node type:Stmt
    class jinja2.nodes.Extends(template)¶

    Represents an extends statement.

    Node type:Stmt
    class jinja2.nodes.FilterBlock(body, filter)¶

    Node for filter sections.

    Node type:Stmt
    class jinja2.nodes.For(target, iter, body, else_, test, recursive)¶

    The for loop. target is the target for the iteration (usually a Name or Tuple), iter the iterable. body is a list of nodes that are used as loop-body, and else_ a list of nodes for the else block. If no else node exists it has to be an empty list.

    For filtered nodes an expression can be stored as test, otherwise None.

    Node type:Stmt
    class jinja2.nodes.FromImport(template, names, with_context)¶

    A node that represents the from import tag. It’s important to not pass unsafe names to the name attribute. The compiler translates the attribute lookups directly into getattr calls and does not use the subscript callback of the interface. As exported variables may not start with double underscores (which the parser asserts) this is not a problem for regular Jinja code, but if this node is used in an extension extra care must be taken.

    The list of names may contain tuples if aliases are wanted.

    Node type:Stmt
    class jinja2.nodes.If(test, body, elif_, else_)¶

    If test is true, body is rendered, else else_.

    Node type:Stmt
    class jinja2.nodes.Import(template, target, with_context)¶

    A node that represents the import tag.

    Node type:Stmt
    class jinja2.nodes.Include(template, with_context, ignore_missing)¶

    A node that represents the include tag.

    Node type:Stmt
    class jinja2.nodes.Macro(name, args, defaults, body)¶

    A macro definition. name is the name of the macro, args a list of arguments and defaults a list of defaults if there are any. body is a list of nodes for the macro body.

    Node type:Stmt
    class jinja2.nodes.Output(nodes)¶

    A node that holds multiple expressions which are then printed out. This is used both for the print statement and the regular template data.

    Node type:Stmt
    class jinja2.nodes.OverlayScope(context, body)¶

    An overlay scope for extensions. This is a largely unoptimized scope that however can be used to introduce completely arbitrary variables into a sub scope from a dictionary or dictionary like object. The context field has to evaluate to a dictionary object.

    Example usage:

    OverlayScope(context=self.call_method('get_context'),
                 body=[...])
    

    New in version 2.10.

    Node type:Stmt
    class jinja2.nodes.Scope(body)¶

    An artificial scope.

    Node type:Stmt
    class jinja2.nodes.With(targets, values, body)¶

    Specific node for with statements. In older versions of Jinja the with statement was implemented on the base of the Scope node instead.

    New in version 2.9.3.

    Node type:Stmt
    class jinja2.nodes.Template(body)¶

    Node that represents a template. This must be the outermost node that is passed to the compiler.

    Node type:Node
    exception jinja2.nodes.Impossible¶

    Raised if the node could not perform a requested action.

    PKê|>]a—Š#‘E‘E html/faq.htmlnu„[µü¤ Frequently Asked Questions — Jinja2 2.10.1 documentation

    Frequently Asked Questions¶

    This page answers some of the often asked questions about Jinja.

    Why is it called Jinja?¶

    The name Jinja was chosen because it’s the name of a Japanese temple and temple and template share a similar pronunciation. It is not named after the city in Uganda.

    How fast is it?¶

    We really hate benchmarks especially since they don’t reflect much. The performance of a template depends on many factors and you would have to benchmark different engines in different situations. The benchmarks from the testsuite show that Jinja2 has a similar performance to Mako and is between 10 and 20 times faster than Django’s template engine or Genshi. These numbers should be taken with tons of salt as the benchmarks that took these numbers only test a few performance related situations such as looping. Generally speaking the performance of a template engine doesn’t matter much as the usual bottleneck in a web application is either the database or the application code.

    How Compatible is Jinja2 with Django?¶

    The default syntax of Jinja2 matches Django syntax in many ways. However this similarity doesn’t mean that you can use a Django template unmodified in Jinja2. For example filter arguments use a function call syntax rather than a colon to separate filter name and arguments. Additionally the extension interface in Jinja is fundamentally different from the Django one which means that your custom tags won’t work any longer.

    Generally speaking you will use much less custom extensions as the Jinja template system allows you to use a certain subset of Python expressions which can replace most Django extensions. For example instead of using something like this:

    {% load comments %}
    {% get_latest_comments 10 as latest_comments %}
    {% for comment in latest_comments %}
        ...
    {% endfor %}
    

    You will most likely provide an object with attributes to retrieve comments from the database:

    {% for comment in models.comments.latest(10) %}
        ...
    {% endfor %}
    

    Or directly provide the model for quick testing:

    {% for comment in Comment.objects.order_by('-pub_date')[:10] %}
        ...
    {% endfor %}
    

    Please keep in mind that even though you may put such things into templates it still isn’t a good idea. Queries should go into the view code and not the template!

    Isn’t it a terrible idea to put Logic into Templates?¶

    Without a doubt you should try to remove as much logic from templates as possible. But templates without any logic mean that you have to do all the processing in the code which is boring and stupid. A template engine that does that is shipped with Python and called string.Template. Comes without loops and if conditions and is by far the fastest template engine you can get for Python.

    So some amount of logic is required in templates to keep everyone happy. And Jinja leaves it pretty much to you how much logic you want to put into templates. There are some restrictions in what you can do and what not.

    Jinja2 neither allows you to put arbitrary Python code into templates nor does it allow all Python expressions. The operators are limited to the most common ones and more advanced expressions such as list comprehensions and generator expressions are not supported. This keeps the template engine easier to maintain and templates more readable.

    Why is Autoescaping not the Default?¶

    There are multiple reasons why automatic escaping is not the default mode and also not the recommended one. While automatic escaping of variables means that you will less likely have an XSS problem it also causes a huge amount of extra processing in the template engine which can cause serious performance problems. As Python doesn’t provide a way to mark strings as unsafe Jinja has to hack around that limitation by providing a custom string class (the Markup string) that safely interacts with safe and unsafe strings.

    With explicit escaping however the template engine doesn’t have to perform any safety checks on variables. Also a human knows not to escape integers or strings that may never contain characters one has to escape or already HTML markup. For example when iterating over a list over a table of integers and floats for a table of statistics the template designer can omit the escaping because he knows that integers or floats don’t contain any unsafe parameters.

    Additionally Jinja2 is a general purpose template engine and not only used for HTML/XML generation. For example you may generate LaTeX, emails, CSS, JavaScript, or configuration files.

    Why is the Context immutable?¶

    When writing a contextfunction() or something similar you may have noticed that the context tries to stop you from modifying it. If you have managed to modify the context by using an internal context API you may have noticed that changes in the context don’t seem to be visible in the template. The reason for this is that Jinja uses the context only as primary data source for template variables for performance reasons.

    If you want to modify the context write a function that returns a variable instead that one can assign to a variable by using set:

    {% set comments = get_latest_comments() %}
    

    My tracebacks look weird. What’s happening?¶

    If the debugsupport module is not compiled and you are using a Python installation without ctypes (Python 2.4 without ctypes, Jython or Google’s AppEngine) Jinja2 is unable to provide correct debugging information and the traceback may be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and it’s not possible to use the debugsupport extension.

    If you are working in the Google AppEngine development server you can whitelist the ctypes module to restore the tracebacks. This however won’t work in production environments:

    import os
    if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
        from google.appengine.tools.devappserver2.python import sandbox
        sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']
    

    Credit for this snippet goes to Thomas Johansson

    Why is there no Python 2.3/2.4/2.5/3.1/3.2 support?¶

    Python 2.3 is missing a lot of features that are used heavily in Jinja2. This decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes harder to maintain the code for older Python versions. If you really need Python 2.3 support you either have to use Jinja 1 or other templating engines that still support 2.3.

    Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting Python 2 and 3 by the same sourcecode (without using 2to3). It was required to drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode literals in a way compatible to each other version. If you really need support for older Python 2 (or 3) versions, you can just use Jinja2 2.6.

    My Macros are overridden by something¶

    In some situations the Jinja scoping appears arbitrary:

    layout.tmpl:

    {% macro foo() %}LAYOUT{% endmacro %}
    {% block body %}{% endblock %}
    

    child.tmpl:

    {% extends 'layout.tmpl' %}
    {% macro foo() %}CHILD{% endmacro %}
    {% block body %}{{ foo() }}{% endblock %}
    

    This will print LAYOUT in Jinja2. This is a side effect of having the parent template evaluated after the child one. This allows child templates passing information to the parent template. To avoid this issue rename the macro or variable in the parent template to have an uncommon prefix.

    PKê|>]ÀRïu½­½­html/genindex.htmlnu„[µü¤ Index — Jinja2 2.10.1 documentation

    Index

    _ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | X

    _

    A

    B

    C

    D

    E

    F

    G

    H

    I

    J

    K

    L

    M

    N

    O

    P

    R

    S

    T

    U

    V

    W

    X

    PKê|>]¢W˜ˆ;N;Nhtml/index.htmlnu„[µü¤ Welcome to Jinja2 — Jinja2 2.10.1 documentation

    Welcome to Jinja2¶

    Jinja2 is a modern and designer-friendly templating language for Python, modelled after Django’s templates. It is fast, widely used and secure with the optional sandboxed template execution environment:

    <title>{% block title %}{% endblock %}</title>
    <ul>
    {% for user in users %}
      <li><a href="{{ user.url }}">{{ user.username }}</a></li>
    {% endfor %}
    </ul>
    

    Features:

    • sandboxed execution
    • powerful automatic HTML escaping system for XSS prevention
    • template inheritance
    • compiles down to the optimal python code just in time
    • optional ahead-of-time template compilation
    • easy to debug. Line numbers of exceptions directly point to the correct line in the template.
    • configurable syntax
    PKê|>]ÄU  ) )html/integration.htmlnu„[µü¤ Integration — Jinja2 2.10.1 documentation

    Integration¶

    Jinja2 provides some code for integration into other tools such as frameworks, the Babel library or your favourite editor for fancy code highlighting. This is a brief description of whats included.

    Files to help integration are available here.

    Babel Integration¶

    Jinja provides support for extracting gettext messages from templates via a Babel extractor entry point called jinja2.ext.babel_extract. The Babel support is implemented as part of the i18n Extension extension.

    Gettext messages extracted from both trans tags and code expressions.

    To extract gettext messages from templates, the project needs a Jinja2 section in its Babel extraction method mapping file:

    [jinja2: **/templates/**.html]
    encoding = utf-8
    

    The syntax related options of the Environment are also available as configuration values in the mapping file. For example to tell the extraction that templates use % as line_statement_prefix you can use this code:

    [jinja2: **/templates/**.html]
    encoding = utf-8
    line_statement_prefix = %
    

    Extensions may also be defined by passing a comma separated list of import paths as extensions value. The i18n extension is added automatically.

    Changed in version 2.7: Until 2.7 template syntax errors were always ignored. This was done since many people are dropping non template html files into the templates folder and it would randomly fail. The assumption was that testsuites will catch syntax errors in templates anyways. If you don’t want that behavior you can add silent=false to the settings and exceptions are propagated.

    Pylons¶

    With Pylons 0.9.7 onwards it’s incredible easy to integrate Jinja into a Pylons powered application.

    The template engine is configured in config/environment.py. The configuration for Jinja2 looks something like that:

    from jinja2 import Environment, PackageLoader
    config['pylons.app_globals'].jinja_env = Environment(
        loader=PackageLoader('yourapplication', 'templates')
    )
    

    After that you can render Jinja templates by using the render_jinja function from the pylons.templating module.

    Additionally it’s a good idea to set the Pylons’ c object into strict mode. Per default any attribute to not existing attributes on the c object return an empty string and not an undefined object. To change this just use this snippet and add it into your config/environment.py:

    config['pylons.strict_c'] = True
    

    TextMate¶

    There is a bundle for TextMate that supports syntax highlighting for Jinja1 and Jinja2 for text based templates as well as HTML. It also contains a few often used snippets.

    Vim¶

    A syntax plugin for Vim exists in the Vim-scripts directory as well as the ext folder at the root of the Jinja2 project. The script supports Jinja1 and Jinja2. Once installed two file types are available jinja and htmljinja. The first one for text based templates, the latter for HTML templates.

    Copy the files into your syntax folder.

    PKê|>]ÀsÁ§0§0html/intro.htmlnu„[µü¤ Introduction — Jinja2 2.10.1 documentation

    Introduction¶

    This is the documentation for the Jinja2 general purpose templating language. Jinja2 is a library for Python that is designed to be flexible, fast and secure.

    If you have any exposure to other text-based template languages, such as Smarty or Django, you should feel right at home with Jinja2. It’s both designer and developer friendly by sticking to Python’s principles and adding functionality useful for templating environments.

    Prerequisites¶

    Jinja2 works with Python 2.6.x, 2.7.x and >= 3.3. If you are using Python 3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.2 was dropped in Jinja2 version 2.7.

    If you wish to use the PackageLoader class, you will also need setuptools or distribute installed at runtime.

    Installation¶

    You have multiple ways to install Jinja2. If you are unsure what to do, go with the Python egg or tarball.

    As a Python egg (via easy_install)¶

    You can install the most recent Jinja2 version using easy_install or pip:

    easy_install Jinja2
    pip install Jinja2
    

    This will install a Jinja2 egg in your Python installation’s site-packages directory.

    From the tarball release¶

    1. Download the most recent tarball from the download page
    2. Unpack the tarball
    3. python setup.py install

    Note that you either have to have setuptools or distribute installed; the latter is preferred.

    This will install Jinja2 into your Python installation’s site-packages directory.

    Installing the development version¶

    1. Install git
    2. git clone git://github.com/pallets/jinja.git
    3. cd jinja2
    4. ln -s jinja2 /usr/lib/python2.X/site-packages

    As an alternative to steps 4 you can also do python setup.py develop which will install the package via distribute in development mode. This also has the advantage that the C extensions are compiled.

    MarkupSafe Dependency¶

    As of version 2.7 Jinja2 depends on the MarkupSafe module. If you install Jinja2 via pip or easy_install it will be installed automatically for you.

    Basic API Usage¶

    This section gives you a brief introduction to the Python API for Jinja2 templates.

    The most basic way to create a template and render it is through Template. This however is not the recommended way to work with it if your templates are not loaded from strings but the file system or another data source:

    >>> from jinja2 import Template
    >>> template = Template('Hello {{ name }}!')
    >>> template.render(name='John Doe')
    u'Hello John Doe!'
    

    By creating an instance of Template you get back a new template object that provides a method called render() which when called with a dict or keyword arguments expands the template. The dict or keywords arguments passed to the template are the so-called “context� of the template.

    What you can see here is that Jinja2 is using unicode internally and the return value is an unicode string. So make sure that your application is indeed using unicode internally.

    Experimental Python 3 Support¶

    Jinja 2.7 brings experimental support for Python >=3.3. It means that all unittests pass on the new version, but there might still be small bugs in there and behavior might be inconsistent. If you notice any bugs, please provide feedback in the Jinja bug tracker.

    Also please keep in mind that the documentation is written with Python 2 in mind, so you will have to adapt the shown code examples to Python 3 syntax for yourself.

    PKê|>]¡i$´ÝBÝBhtml/latexindex.htmlnu„[µü¤ Jinja2 Documentation — Jinja2 2.10.1 documentation

    Jinja2 Documentation¶

    PKê|>]�>4éC1C1html/nativetypes.htmlnu„[µü¤ Native Python Types — Jinja2 2.10.1 documentation

    Native Python Types¶

    The default Environment renders templates to strings. With NativeEnvironment, rendering a template produces a native Python type. This is useful if you are using Jinja outside the context of creating text files. For example, your code may have an intermediate step where users may use templates to define values that will then be passed to a traditional string environment.

    Examples¶

    Adding two values results in an integer, not a string with a number:

    >>> env = NativeEnvironment()
    >>> t = env.from_string('{{ x + y }}')
    >>> result = t.render(x=4, y=2)
    >>> print(result)
    6
    >>> print(type(result))
    int
    

    Rendering list syntax produces a list:

    >>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]')
    >>> result = t.render(data=range(5))
    >>> print(result)
    [1, 2, 3, 4, 5]
    >>> print(type(result))
    list
    

    Rendering something that doesn’t look like a Python literal produces a string:

    >>> t = env.from_string('{{ x }} * {{ y }}')
    >>> result = t.render(x=4, y=2)
    >>> print(result)
    4 * 2
    >>> print(type(result))
    str
    

    Rendering a Python object produces that object as long as it is the only node:

    >>> class Foo:
    ...     def __init__(self, value):
    ...         self.value = value
    ...
    >>> result = env.from_string('{{ x }}').render(x=Foo(15))
    >>> print(type(result).__name__)
    Foo
    >>> print(result.value)
    15
    

    API¶

    class jinja2.nativetypes.NativeEnvironment([options])¶

    An environment that renders templates to native Python types.

    class jinja2.nativetypes.NativeTemplate([options])¶
    render(*args, **kwargs)¶

    Render the template to produce a native Python type. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with ast.literal_eval(), the parsed value is returned. Otherwise, the string is returned.

    PKê|>]QÎñ†ß ß html/objects.invnu„[µü¤# Sphinx inventory version 2 # Project: Jinja2 # Version: 2.10 # The remainder of this file is compressed using zlib. xÚµ\Ks㸾óW°*¹R•ÝSjo¶ÇÞ8™ñ8koæÈ‚HHÂ8hKùõi�àK¢Änzr™õ}�&Ðht7²µ�Ëão›JeNhÿ;^”’9nW;WÈ¿ü5N"朙G­™Ëvó°ŒIÉÖ’c�¥pLŠÿb°\9ŽP2;f²Áe’Y{ ´Ê*c@¬ûëÊñ«Å5ºàn§ó«PÃ-ŸÅæ|Ã*éæß €Bñ™Ã¡¬6(ä›°Fs}œóŒ…QçXâ�ùWó¨��Ü‚¡m´)˜Ãà�ÅÀ¤FIÓ&ãØ7Ǫ¸EÈÚ]•˜¡Û" ƒÉÃŒšÃa@0ãqžä»PßÙ¯õtÓyŒ¿ÅÙŽ©-—zÛ šçI^Ý2Ë?k–�½¸¤S±äjË]juÃ9šÛ3,°’|t<Ó9¿cَϪ4¯Àã0Ck`•WE™®Ã#"׿ž{·Ó"Cvõ'¾®¶ª�¿»Š?†“{¯Þ„ѪƉ„®Xž§àó¹²Þôæ^tÈô=“n¹ vÚ¤Mƒ' ͼŒ¢¿”°œ,P¡¡wó…Ȇ÷à–i^÷YNj(†e.…?•uámÇ wã`¯ÊOnƒ¬ñÆè"µ€W[’ÚÞ!ÀøZ.¹W>t5YÄ2¢Ôk&ɯ*”…¨K‚uºf„CÀ¶¨»O…}tøZyª‚?>*ì»*-™Û‘ºUò /¬[8Éô7’Iœ’K³“RK‘ N6ð:¥Ñ·´—²Låk}hÜ7¥½�L"»c†Þ"Œ—#wK5\žÐ VêgL•pè/G ]D zn¹|Ñý…™}UâP«> ®ÁWû/P¼[.ÛΛa Tªoå:ž™ï¿œÔ›Ó¬Õ¡DÁä�0Þ�>]ݰìç ókÅ—º$Ñb$ÖÁ3ΞY¶g[,ØÀL:à°/`™Cdž¯/‚Á­ÖRg{”3è(>«T¬à$R ç�óŒ‘2{T�‡�:ްiU¦N§yPÍ,Øž§!ýB«ØãÑí�;\ñ÷4D³xŠįÜPñÔ2Z»4P}†‹g‚Oä¬@ão¬åÆ{ô{ctýZü�ñ2dÔטd“vºj¢,ç�J9QÐÛz9*Ç¡-šÃC¾g¤ôRvÁÛ.nœª¸¥ ÚÕvÀUºaB¦ïÂíÒ.JJy;ß@�Þ�€µÝd]üKk §[=“ðf%lÊ$|‹šg F©wZÝruÍV/3W¹°¾F‘®«Í†£Lîš°ª(?‡c±.èŽr�?µË0 |c’j CA¥wµ•ùÓôö¼4ˆÕý°ìÚÍ•ÌxÄYµ;š˜œzÌôÕ°4Ð hz3�ÐÐ"„ßDÑ ÊÐa¡EœW‰ðÔ鲚ßfêH½}Æ¡¦78§¬Iò7«W½çXË0.DkH²¯a»ä”—2u\Ä=–|¡º0Y«…ÜswMá­ÒÔï”§é‚.lÍ“dpm?Æ?”ƒÄÄ�å¼ûIzÊ\a×…©·[X‰I®Tcà®U)8,ä\e¶� ùh¾Y˜*¼1#ºí”Š9ñÆý·£%rðüÒ9„<Õÿ¾°Çy&ëª�©²Ù2 S%”«’ صÄ@¡æ¬nòéª^ñÖŠ­Z@¹õ%EïV¨ûCihz+0IiŒ;ˆŠÈºbwº€À…9*cŽJÉÉÝ $KnƇÊ´Î…Lª¢‘>…ã_ ?ð17ݺJQÉ]_Œ½– žV¬rºOpæùsþ›öÛmrû‹Î»�ÿºT+ó„³¾`�6ÔŒ©”uþŠF~q…#*ë�yX:Ç–ÙÏC—«)tgôœ¡N�MTÎèâ±(ÃaL4íwˆ âêô¹>^I[Õ¿°Ìh"Ãì_؆/"=nnF/@Ó:ïKE뇧XÔi ª <ñ- ¯‰Öé uòB[(:ZBB"Õ[]ší„ÌÓ>â_ –b™/a[îÒÌ2O¶ HèKP2mn§ÍˆYÎWš›ÿZ¹²"jÕœv{É4q:?3ASîY["þ�„§¿BÍÈ?N¾HAL#È1ÝKµ&á§ hÒ'æ‘H\å^«RÒtûS1s$ÇíßDsÊA¨KóŒÚÿµ„³ò»ìXr¼pÚ/ÀpžŽ÷'èZ|Hƒú!ÇI3§G∂.®'J±Žs¿(Ø�Hq­±ÒôÛMÈN5Í‘›2?�NË�2³Ó¸C"îüŸÑÁï¶‹>™{h² _Ø]ôÂþ|ÿ’wö¼¶q2{tå”çËoËúf‘–oœ¬)¶[ñòQ…8<»Tn~,ŠÊùšüK{4ýB­|$oBÐÿƒßì8¯…Ò㠗岪Ÿ"*\Nm4K]{o8L’[ý\±Â'Û>¡‡™Z«lºØêçIµ©…ü6eÃØÇ†«9¼~�—ȳÊwœ<ƒ6G†–E¨tŒ_h°ù5'£h¢a›î•~Wi˜®D!•²¡Ò€!5—MÆ%å‹ÛusùÕ£fïžÃ/ˆ«¯˜K¯ÉmâB¾¥­ ¥™~ÇÜÃÇÜj/X‰•áˆÕð€aÆÑ¯�¶<¹»1…C ’Ò(TU¬1½ªsÄ�ø²4¨ëÕ¾B  s×Üðïóñ�‡ûä„áð$C5þÆÃ�§`{úù:l‘L¢ Îß×h| ‡ëËTí¦â ²-ÌÀP„èÏûÎãº;[3PŒsrÂa|¢Óß­FLqÐÓ(Īsˆv/;™„ŠFdYb\Be`h ÏBQßZñ{õaôÝ`üø¡�8Ãf™?zF–¸Oš|$‘BZëòß ¶á2N€i$ -í¦%ÅÎßßk’˜Ï@Š`¯‰¹Î<­]Öã›çǨ)"4iûXø©Z7=2êC†¤ÿ6Àˆ~žvö1º С Ø_ŸÑ£—óµ¥DkO| ¶5õuÒ±�Á­˜Ûú·Çþ‡(äó×[¯÷P¡½JH'TÒ^µ¿Nª7¦ô&¾mXq³ÛKio©á¤ü^£ãö‚j/¦¹ÊKSÅWAB8iŸÔgèÇ"Q`{›2®¯SÖŸ9šiΟ�‰ºï� ­püq’øŸ>$�ïÚ‡Q¦ ŒQÞXäËI{Åí’þ¾ö\5æR隷}Í5uß#�åñËß¡ËÁ‰àò.µ˜D<˜^£¢~Ú ûêd2õóÇFöcˆ„ÿ6�S/ŽNaâîAÃW0Ò e³­�n´™r=gpm¢-Wþã7‡1´}Úèõèÿ5ŸôQæ¥þ{k öþÔ‚£ºçÑ~Ç£§&ד¥=äxýÅ<>꫽^gïc/)ü¤½HÐê±£ØHlfyÜ&ÔaçàkŒDs|`†Rƒ6©¿h%$¤»(Z;[â[¾co†ºç`xƒ!þÆ%Ì^;ÝÌê_£S¿ÜqÆ^yä�áG£OÐFw8£óªvM2›œLœ+ö0˜<þUg¯Ò?¸¦_ãO:«¼¯iÔó[˜É ä=çu!zéÐuž™èMí°Œ– ÈÀÛT†cÝ÷]C™-1’õr{Ñ2›+æ§Ë°n�òd²«Ë ¦ÅO:w´Jú&ß é‰LÚPdZÁ÷ø³GÕ�IáÏYÌuG}ÃF¾trîxÊcÒþÐ ds‡?¸ á¹ãÁàŸÏ�›½ñóÑíàµ_ýgܮɉý“|þnÝQò$|c®7¿í„ ŽòÕ/80n�UãD«ÄVk›ùL±†ù4[ʤ`F?ÙÀâ¼fÙþZTùäñ_j|üðQ÷5•KCùQ[±ôð°‡:¤rÌd»±¼æYÀ5¿?³-�ì»pÙ®µÝVjû0à;Œ¿äk‰MÜíÓÞ«­?_µýëü.S§KÑYv2{J4^K‚FcjOüÄ} êŒ &xk‚µf€FMõC¿ŠÒÆþàÃký0êÏâ_—ýŸù»Ëø™^ïúv®-ò77}â‚÷Ç߯Ð/·B&#•�™ÝUÖÁè¶¡JK›èÊsRÓ—ÿä_¦ PKê|>]ï* ³UUhtml/py-modindex.htmlnu„[µü¤ Python Module Index — Jinja2 2.10.1 documentation

    Python Module Index

    j
     
    j
    jinja2
        jinja2.ext
        jinja2.nativetypes
        jinja2.nodes
        jinja2.sandbox
    PKê|>]"…z92f2fhtml/sandbox.htmlnu„[µü¤ Sandbox — Jinja2 2.10.1 documentation

    Sandbox¶

    The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited.

    Assuming env is a SandboxedEnvironment in the default configuration the following piece of code shows how it works:

    >>> env.from_string("{{ func.func_code }}").render(func=lambda:None)
    u''
    >>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)
    Traceback (most recent call last):
      ...
    SecurityError: access to attribute 'func_code' of 'function' object is unsafe.
    

    API¶

    class jinja2.sandbox.SandboxedEnvironment([options])¶

    The sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes or functions are safe to access.

    If the template tries to access insecure code a SecurityError is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught.

    call_binop(context, operator, left, right)¶

    For intercepted binary operator calls (intercepted_binops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

    New in version 2.6.

    call_unop(context, operator, arg)¶

    For intercepted unary operator calls (intercepted_unops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

    New in version 2.6.

    default_binop_table = {'%': <built-in function mod>, '*': <built-in function mul>, '**': <built-in function pow>, '+': <built-in function add>, '-': <built-in function sub>, '/': <built-in function truediv>, '//': <built-in function floordiv>}¶

    default callback table for the binary operators. A copy of this is available on each instance of a sandboxed environment as binop_table

    default_unop_table = {'+': <built-in function pos>, '-': <built-in function neg>}¶

    default callback table for the unary operators. A copy of this is available on each instance of a sandboxed environment as unop_table

    intercepted_binops = frozenset()¶

    a set of binary operators that should be intercepted. Each operator that is added to this set (empty by default) is delegated to the call_binop() method that will perform the operator. The default operator callback is specified by binop_table.

    The following binary operators are interceptable: //, %, +, *, -, /, and **

    The default operation form the operator table corresponds to the builtin function. Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in.

    New in version 2.6.

    intercepted_unops = frozenset()¶

    a set of unary operators that should be intercepted. Each operator that is added to this set (empty by default) is delegated to the call_unop() method that will perform the operator. The default operator callback is specified by unop_table.

    The following unary operators are interceptable: +, -

    The default operation form the operator table corresponds to the builtin function. Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in.

    New in version 2.6.

    is_safe_attribute(obj, attr, value)¶

    The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the is_internal_attribute() function.

    is_safe_callable(obj)¶

    Check if an object is safely callable. Per default a function is considered safe unless the unsafe_callable attribute exists and is True. Override this method to alter the behavior, but this won’t affect the unsafe decorator from this module.

    class jinja2.sandbox.ImmutableSandboxedEnvironment([options])¶

    Works exactly like the regular SandboxedEnvironment but does not permit modifications on the builtin mutable objects list, set, and dict by using the modifies_known_mutable() function.

    exception jinja2.sandbox.SecurityError(message=None)¶

    Raised if a template tries to do something insecure if the sandbox is enabled.

    jinja2.sandbox.unsafe(f)¶

    Marks a function or method as unsafe.

    @unsafe
    def delete(self):
        pass
    
    jinja2.sandbox.is_internal_attribute(obj, attr)¶

    Test if the attribute given is an internal python attribute. For example this function returns True for the func_code attribute of python objects. This is useful if the environment method is_safe_attribute() is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    
    jinja2.sandbox.modifies_known_mutable(obj, attr)¶

    This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the “user�-versions of the objects (sets.Set, UserDict.* etc.) and with Python 2.6 onwards the abstract base classes MutableSet, MutableMapping, and MutableSequence.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False
    

    If called with an unsupported object (such as unicode) False is returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    

    Note

    The Jinja2 sandbox alone is no solution for perfect security. Especially for web applications you have to keep in mind that users may create templates with arbitrary HTML in so it’s crucial to ensure that (if you are running multiple users on the same server) they can’t harm each other via JavaScript insertions and much more.

    Also the sandbox is only as good as the configuration. We strongly recommend only passing non-shared resources to the template and use some sort of whitelisting for attributes.

    Also keep in mind that templates may raise runtime or compile time errors, so make sure to catch them.

    Operator Intercepting¶

    New in version 2.6.

    For maximum performance Jinja2 will let operators call directly the type specific callback methods. This means that it’s not possible to have this intercepted by overriding Environment.call(). Furthermore a conversion from operator to special method is not always directly possible due to how operators work. For instance for divisions more than one special method exist.

    With Jinja 2.6 there is now support for explicit operator intercepting. This can be used to customize specific operators as necessary. In order to intercept an operator one has to override the SandboxedEnvironment.intercepted_binops attribute. Once the operator that needs to be intercepted is added to that set Jinja2 will generate bytecode that calls the SandboxedEnvironment.call_binop() function. For unary operators the unary attributes and methods have to be used instead.

    The default implementation of SandboxedEnvironment.call_binop will use the SandboxedEnvironment.binop_table to translate operator symbols into callbacks performing the default operator behavior.

    This example shows how the power (**) operator can be disabled in Jinja2:

    from jinja2.sandbox import SandboxedEnvironment
    
    
    class MyEnvironment(SandboxedEnvironment):
        intercepted_binops = frozenset(['**'])
    
        def call_binop(self, context, operator, left, right):
            if operator == '**':
                return self.undefined('the power operator is unavailable')
            return SandboxedEnvironment.call_binop(self, context,
                                                   operator, left, right)
    

    Make sure to always call into the super method, even if you are not intercepting the call. Jinja2 might internally call the method to evaluate expressions.

    PKê|>]¤žmëê ê html/search.htmlnu„[µü¤ Search — Jinja2 2.10.1 documentation

    Search

    Please activate JavaScript to enable the search functionality.

    From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list.

    PKê|>]�J¡¬Œ™Œ™html/searchindex.jsnu„[µü¤Search.setIndex({docnames:["api","changelog","extensions","faq","index","integration","intro","latexindex","nativetypes","sandbox","switching","templates","tricks"],envversion:53,filenames:["api.rst","changelog.rst","extensions.rst","faq.rst","index.rst","integration.rst","intro.rst","latexindex.rst","nativetypes.rst","sandbox.rst","switching.rst","templates.rst","tricks.rst"],objects:{"":{"default":[11,0,1,""],"float":[11,0,1,""],"in":[11,0,1,""],"int":[11,0,1,""],abs:[11,0,1,""],attr:[11,0,1,""],batch:[11,0,1,""],callable:[11,0,1,""],capitalize:[11,0,1,""],center:[11,0,1,""],cycler:[11,1,1,""],defined:[11,0,1,""],dict:[11,0,1,""],dictsort:[11,0,1,""],divisibleby:[11,0,1,""],eq:[11,0,1,""],escape:[11,0,1,""],escaped:[11,0,1,""],even:[11,0,1,""],filesizeformat:[11,0,1,""],first:[11,0,1,""],forceescape:[11,0,1,""],format:[11,0,1,""],ge:[11,0,1,""],groupby:[11,0,1,""],gt:[11,0,1,""],indent:[11,0,1,""],iterable:[11,0,1,""],jinja2:[1,4,0,"-"],join:[11,0,1,""],joiner:[11,1,1,""],last:[11,0,1,""],le:[11,0,1,""],length:[11,0,1,""],lipsum:[11,0,1,""],list:[11,0,1,""],lower:[11,0,1,""],lt:[11,0,1,""],map:[11,0,1,""],mapping:[11,0,1,""],max:[11,0,1,""],min:[11,0,1,""],namespace:[11,1,1,""],ne:[11,0,1,""],none:[11,0,1,""],number:[11,0,1,""],odd:[11,0,1,""],pprint:[11,0,1,""],random:[11,0,1,""],range:[11,0,1,""],reject:[11,0,1,""],rejectattr:[11,0,1,""],replace:[11,0,1,""],reverse:[11,0,1,""],round:[11,0,1,""],safe:[11,0,1,""],sameas:[11,0,1,""],select:[11,0,1,""],selectattr:[11,0,1,""],sequence:[11,0,1,""],slice:[11,0,1,""],sort:[11,0,1,""],string:[11,0,1,""],striptags:[11,0,1,""],sum:[11,0,1,""],title:[11,0,1,""],tojson:[11,0,1,""],trim:[11,0,1,""],truncate:[11,0,1,""],undefined:[11,0,1,""],unique:[11,0,1,""],upper:[11,0,1,""],urlencode:[11,0,1,""],urlize:[11,0,1,""],wordcount:[11,0,1,""],wordwrap:[11,0,1,""],xmlattr:[11,0,1,""]},"jinja2.BaseLoader":{get_source:[0,3,1,""],load:[0,3,1,""]},"jinja2.BytecodeCache":{clear:[0,3,1,""],dump_bytecode:[0,3,1,""],load_bytecode:[0,3,1,""]},"jinja2.Environment":{add_extension:[0,3,1,""],code_generator_class:[0,2,1,""],compile_expression:[0,3,1,""],compile_templates:[0,3,1,""],context_class:[0,2,1,""],extend:[0,3,1,""],extract_translations:[2,3,1,""],filters:[0,2,1,""],from_string:[0,3,1,""],get_or_select_template:[0,3,1,""],get_template:[0,3,1,""],globals:[0,2,1,""],install_gettext_callables:[2,3,1,""],install_gettext_translations:[2,3,1,""],install_null_translations:[2,3,1,""],join_path:[0,3,1,""],lex:[0,3,1,""],list_templates:[0,3,1,""],overlay:[0,3,1,""],parse:[0,3,1,""],policies:[0,2,1,""],preprocess:[0,3,1,""],sandboxed:[0,2,1,""],select_template:[0,3,1,""],shared:[0,2,1,""],tests:[0,2,1,""],undefined:[0,3,1,""],uninstall_gettext_translations:[2,3,1,""]},"jinja2.Markup":{escape:[0,5,1,""],striptags:[0,3,1,""],unescape:[0,3,1,""]},"jinja2.MemcachedBytecodeCache":{MinimalClientInterface:[0,1,1,""]},"jinja2.MemcachedBytecodeCache.MinimalClientInterface":{get:[0,3,1,""],set:[0,3,1,""]},"jinja2.Template":{blocks:[0,2,1,""],filename:[0,2,1,""],generate:[0,3,1,""],generate_async:[0,3,1,""],globals:[0,2,1,""],is_up_to_date:[0,2,1,""],make_module:[0,3,1,""],module:[0,2,1,""],name:[0,2,1,""],new_context:[0,3,1,""],render:[0,3,1,""],render_async:[0,3,1,""],root_render_func:[0,3,1,""],stream:[0,3,1,""]},"jinja2.TemplateSyntaxError":{filename:[0,2,1,""],lineno:[0,2,1,""],message:[0,2,1,""],name:[0,2,1,""]},"jinja2.Undefined":{_fail_with_undefined_error:[0,3,1,""],_undefined_exception:[0,2,1,""],_undefined_hint:[0,2,1,""],_undefined_name:[0,2,1,""],_undefined_obj:[0,2,1,""]},"jinja2.bccache":{Bucket:[0,1,1,""]},"jinja2.bccache.Bucket":{bytecode_from_string:[0,3,1,""],bytecode_to_string:[0,3,1,""],code:[0,2,1,""],environment:[0,2,1,""],key:[0,2,1,""],load_bytecode:[0,3,1,""],reset:[0,3,1,""],write_bytecode:[0,3,1,""]},"jinja2.environment":{TemplateStream:[0,1,1,""]},"jinja2.environment.TemplateStream":{disable_buffering:[0,3,1,""],dump:[0,3,1,""],enable_buffering:[0,3,1,""]},"jinja2.ext":{Extension:[2,1,1,""]},"jinja2.ext.Extension":{attr:[2,3,1,""],call_method:[2,3,1,""],filter_stream:[2,3,1,""],identifier:[2,2,1,""],parse:[2,3,1,""],preprocess:[2,3,1,""],tags:[2,2,1,""]},"jinja2.lexer":{Token:[2,1,1,""],TokenStream:[2,1,1,""],count_newlines:[2,0,1,""]},"jinja2.lexer.Token":{lineno:[2,2,1,""],test:[2,3,1,""],test_any:[2,3,1,""],type:[2,2,1,""],value:[2,2,1,""]},"jinja2.lexer.TokenStream":{__next__:[2,3,1,""],current:[2,2,1,""],eos:[2,2,1,""],expect:[2,3,1,""],look:[2,3,1,""],next_if:[2,3,1,""],push:[2,3,1,""],skip:[2,3,1,""],skip_if:[2,3,1,""]},"jinja2.meta":{find_referenced_templates:[0,0,1,""],find_undeclared_variables:[0,0,1,""]},"jinja2.nativetypes":{NativeEnvironment:[8,1,1,""],NativeTemplate:[8,1,1,""]},"jinja2.nativetypes.NativeTemplate":{render:[8,3,1,""]},"jinja2.nodes":{Add:[2,1,1,""],And:[2,1,1,""],Assign:[2,1,1,""],AssignBlock:[2,1,1,""],BinExpr:[2,1,1,""],Block:[2,1,1,""],Break:[2,1,1,""],Call:[2,1,1,""],CallBlock:[2,1,1,""],Compare:[2,1,1,""],Concat:[2,1,1,""],CondExpr:[2,1,1,""],Const:[2,1,1,""],ContextReference:[2,1,1,""],Continue:[2,1,1,""],Dict:[2,1,1,""],Div:[2,1,1,""],EnvironmentAttribute:[2,1,1,""],EvalContext:[0,1,1,""],EvalContextModifier:[2,1,1,""],Expr:[2,1,1,""],ExprStmt:[2,1,1,""],Extends:[2,1,1,""],ExtensionAttribute:[2,1,1,""],Filter:[2,1,1,""],FilterBlock:[2,1,1,""],FloorDiv:[2,1,1,""],For:[2,1,1,""],FromImport:[2,1,1,""],Getattr:[2,1,1,""],Getitem:[2,1,1,""],Helper:[2,1,1,""],If:[2,1,1,""],Import:[2,1,1,""],ImportedName:[2,1,1,""],Impossible:[2,6,1,""],Include:[2,1,1,""],InternalName:[2,1,1,""],Keyword:[2,1,1,""],List:[2,1,1,""],Literal:[2,1,1,""],Macro:[2,1,1,""],MarkSafe:[2,1,1,""],MarkSafeIfAutoescape:[2,1,1,""],Mod:[2,1,1,""],Mul:[2,1,1,""],NSRef:[2,1,1,""],Name:[2,1,1,""],Neg:[2,1,1,""],Node:[2,1,1,""],Not:[2,1,1,""],Operand:[2,1,1,""],Or:[2,1,1,""],Output:[2,1,1,""],OverlayScope:[2,1,1,""],Pair:[2,1,1,""],Pos:[2,1,1,""],Pow:[2,1,1,""],Scope:[2,1,1,""],ScopedEvalContextModifier:[2,1,1,""],Slice:[2,1,1,""],Stmt:[2,1,1,""],Sub:[2,1,1,""],Template:[2,1,1,""],TemplateData:[2,1,1,""],Test:[2,1,1,""],Tuple:[2,1,1,""],UnaryExpr:[2,1,1,""],With:[2,1,1,""]},"jinja2.nodes.EvalContext":{"volatile":[0,2,1,""],autoescape:[0,2,1,""]},"jinja2.nodes.Expr":{as_const:[2,3,1,""],can_assign:[2,3,1,""]},"jinja2.nodes.Node":{find:[2,3,1,""],find_all:[2,3,1,""],iter_child_nodes:[2,3,1,""],iter_fields:[2,3,1,""],set_ctx:[2,3,1,""],set_environment:[2,3,1,""],set_lineno:[2,3,1,""]},"jinja2.parser":{Parser:[2,1,1,""]},"jinja2.parser.Parser":{fail:[2,3,1,""],filename:[2,2,1,""],free_identifier:[2,3,1,""],name:[2,2,1,""],parse_assign_target:[2,3,1,""],parse_expression:[2,3,1,""],parse_statements:[2,3,1,""],parse_tuple:[2,3,1,""],stream:[2,2,1,""]},"jinja2.runtime":{Context:[0,1,1,""]},"jinja2.runtime.Context":{blocks:[0,2,1,""],call:[0,3,1,""],environment:[0,2,1,""],eval_ctx:[0,2,1,""],exported_vars:[0,2,1,""],get_all:[0,3,1,""],get_exported:[0,3,1,""],name:[0,2,1,""],parent:[0,2,1,""],resolve:[0,3,1,""],vars:[0,2,1,""]},"jinja2.sandbox":{ImmutableSandboxedEnvironment:[9,1,1,""],SandboxedEnvironment:[9,1,1,""],SecurityError:[9,6,1,""],is_internal_attribute:[9,0,1,""],modifies_known_mutable:[9,0,1,""],unsafe:[9,0,1,""]},"jinja2.sandbox.SandboxedEnvironment":{call_binop:[9,3,1,""],call_unop:[9,3,1,""],default_binop_table:[9,2,1,""],default_unop_table:[9,2,1,""],intercepted_binops:[9,2,1,""],intercepted_unops:[9,2,1,""],is_safe_attribute:[9,3,1,""],is_safe_callable:[9,3,1,""]},cycler:{current:[11,2,1,""],next:[11,3,1,""],reset:[11,3,1,""]},jinja2:{BaseLoader:[0,1,1,""],BytecodeCache:[0,1,1,""],ChoiceLoader:[0,1,1,""],DebugUndefined:[0,1,1,""],DictLoader:[0,1,1,""],Environment:[0,1,1,""],FileSystemBytecodeCache:[0,1,1,""],FileSystemLoader:[0,1,1,""],FunctionLoader:[0,1,1,""],Markup:[0,1,1,""],MemcachedBytecodeCache:[0,1,1,""],ModuleLoader:[0,1,1,""],PackageLoader:[0,1,1,""],PrefixLoader:[0,1,1,""],StrictUndefined:[0,1,1,""],Template:[0,1,1,""],TemplateAssertionError:[0,6,1,""],TemplateError:[0,6,1,""],TemplateNotFound:[0,6,1,""],TemplateRuntimeError:[0,6,1,""],TemplateSyntaxError:[0,6,1,""],TemplatesNotFound:[0,6,1,""],Undefined:[0,1,1,""],UndefinedError:[0,6,1,""],clear_caches:[0,0,1,""],contextfilter:[0,0,1,""],contextfunction:[0,0,1,""],environmentfilter:[0,0,1,""],environmentfunction:[0,0,1,""],escape:[0,0,1,""],evalcontextfilter:[0,0,1,""],evalcontextfunction:[0,0,1,""],ext:[2,4,0,"-"],is_undefined:[0,0,1,""],make_logging_undefined:[0,0,1,""],nativetypes:[8,4,0,"-"],nodes:[2,4,0,"-"],sandbox:[9,4,0,"-"],select_autoescape:[0,0,1,""]}},objnames:{"0":["py","function","Python function"],"1":["py","class","Python class"],"2":["py","attribute","Python attribute"],"3":["py","method","Python method"],"4":["py","module","Python module"],"5":["py","classmethod","Python class method"],"6":["py","exception","Python exception"]},objtypes:{"0":"py:function","1":"py:class","2":"py:attribute","3":"py:method","4":"py:module","5":"py:classmethod","6":"py:exception"},terms:{"0rc1":[4,7],"10th":[1,11],"13th":1,"14th":1,"17th":1,"18th":1,"19th":1,"20th":1,"23rd":1,"24th":1,"25th":1,"26th":1,"28th":1,"29th":1,"2to3":3,"3rd":1,"64bit":1,"6th":1,"7th":1,"8th":1,"9th":1,"abstract":[0,2,9],"boolean":[0,11],"break":[0,1,2,11],"byte":[3,11],"case":[0,1,2,11],"catch":[0,5,9],"char":11,"class":[0,1,2,3,6,8,9,10,11,12],"const":2,"default":[0,1,2,4,5,7,8,9,10,11,12],"export":[0,2,11],"f\u00f6\u00f6":0,"final":[0,1],"float":[3,11],"function":[0,1,2,3,4,5,6,7,9,10],"h\u00e4nsel":0,"import":[0,1,2,3,4,5,6,7,9,10],"int":[0,1,8,11],"long":[0,1,8,11,12],"new":[0,1,2,6,9,10,11],"null":[4,7,11],"public":[0,12],"return":[0,1,2,3,5,6,8,9,11],"short":[0,2],"super":[2,9],"switch":[0,1,2,3,4,7],"true":[0,2,5,9,11,12],"try":[0,2,3,4],"var":0,"while":[1,3,10,12],"yasuz\u014d":1,AND:2,Added:[0,1,11],Adding:[4,7,8],And:[2,3],Are:2,But:[3,11],For:[0,1,2,3,5,8,9,10],Not:[0,2],One:[0,2],Pos:2,That:[0,11],The:[1,2,3,4,5,6,7,8,9,10,11,12],Then:[2,11],There:[0,1,2,3,5,10,11],These:[0,1,2,3,11],Use:[0,2,11],Useful:11,Using:0,With:[0,1,3,4,5,7,8,9,10],__call__:[1,11],__contains__:0,__float__:0,__future__:11,__getitem__:[0,11],__html__:[0,11],__init__:[0,2,8],__int__:0,__iter__:0,__jinja2_:0,__name__:[0,8],__next__:2,__underscore__:0,__unicode__:0,_blank:11,_cache_support:2,_client:0,_ctype:3,_fail_with_undefined_error:0,_grouptupl:1,_my_attribut:2,_paragraph_r:0,_speedup:1,_undefined_except:0,_undefined_hint:0,_undefined_nam:0,_undefined_obj:0,_white_list_c_modul:3,a_vari:11,aaaaargh:11,aaargh:11,abil:1,abl:[0,1,2,10,11],abort:[0,1],about:[0,3,10,11,12],abov:[10,11],abs:11,absolut:[1,11],accept:[0,1,2,11],access:[0,1,2,4,7,9,10,11],achiev:[10,12],across:[1,11],act:[2,11],action:[2,11],activ:[0,2,4,7,11],active_pag:12,actual:[0,1,2,10],adapt:6,add:[0,1,2,5,9,11,12],add_extens:0,added:[0,1,2,5,9,11,12],adding:[0,1,2,6,11],addit:[2,10,11],addition:[0,3,5,9,10,11,12],address:11,adjac:11,advanc:[0,3],advantag:[0,1,2,6,10,11],advertis:1,affect:[9,11],after:[0,1,2,3,4,5,11],afterward:11,again:[0,2],against:[0,2,11],ahead:[2,4,11],aka:2,albeit:0,algorithm:0,alia:[1,10,11,12],alias:[2,11],all:[0,1,2,3,6,9,11],allow:[0,1,2,3,10,11],alon:9,alreadi:[0,1,3,11],also:[0,1,2,3,5,6,9,10,11],alter:[0,9],altern:[4,6,7,11],alwai:[0,1,2,5,9,11,12],among:11,amount:[3,12],amp:0,ani:[0,2,3,5,6,10,11],anonym:0,anoth:[0,2,6,10,11],ansibl:1,answer:3,anyth:[0,2,11],anywai:[1,5,11],anywher:11,apart:11,api:[1,3,4,7],app1:0,app2:0,app_glob:5,appear:[0,3,11],append:[2,9,11],appengin:3,appl:[2,11],appli:[0,1,2,11],applic:[0,1,2,3,5,6,9,10,11],approach:11,appropri:2,april:1,arbitrari:[0,1,2,3,9],architectur:1,area:1,arg:[0,2,8,9,11],argument:[0,1,2,3,6,11],arithmet:11,around:[1,2,3,10,11],articl:0,artifici:2,as_const:2,ascend:11,ascii:[0,1,2,10],ascii_str:[0,1],asciif:1,ask:[0,4,7],assert:2,assign:[0,1,2,3,10,12],assignblock:2,assum:[0,9,11],assumpt:[1,5],ast:[0,1,8],async:[1,4,7],asynchron:0,asyncio:0,attach:[0,2],attempt:11,attr:[0,2,9,11],attribut:[0,1,2,3,5,9,10,11],august:1,author:11,auto:[0,11],auto_reload:0,autoescap:[1,4,7],automat:[0,1,2,3,4,5,6,10],autoreload:0,autospac:11,avail:[0,1,2,5,9,10,11],avait:0,avoid:[0,3,11],awai:0,await:0,awar:0,awesom:11,babel:[1,2,4,7,10],babel_extract:5,back:[0,1,2,6,11],backward:[0,1,2],bad:1,badli:[0,1],bar:[0,1,2,11,12],bare:1,bark:0,base:[0,1,2,5,6,9],baseclass:[0,2],baseload:0,basestr:[0,11],basi:0,basic:[4,7,10,11,12],bastard:11,batch:11,baz:[2,11],bcc:0,bccach:0,becam:[1,10],becaus:[0,1,2,3,10,11,12],becom:[2,3,11],been:11,befor:[0,1,2,11,12],begin:[0,11],behav:[0,2],behavior:[0,1,4,5,6,7,9,12],behaviour:0,behind:0,being:[0,1,10,12],below:[0,2,11],benchmark:3,benefit:0,besid:[0,11],better:[0,1,2,11],between:[1,2,3,10,11,12],big:[0,1,2],bigger:11,binari:[0,1,2,9,11],bind:11,binexpr:2,binop_t:9,bit:10,blank:[1,11],blink:0,block:[0,1,2,3,4,10,12],block_end_str:0,block_start_str:0,blocknam:11,bodi:[1,2,3,10,11,12],bogu:2,book:11,book_titl:11,bore:3,both:[0,2,5,6,11],bottleneck:3,bound:[0,2],box:11,brace:11,bracket:[1,11],branch:11,break_long_word:11,brief:[5,6],bring:6,broke:1,broken:1,browser:11,bucket:0,buffer:[0,1,2],bug:[1,6,11],bugfix:1,buggi:1,build:[0,2,11],built:[0,1,2,9,11],builtin:[0,1,4,7,9],bundl:5,bytecod:[1,4,7,9],bytecode_cach:0,bytecode_from_str:0,bytecode_to_str:0,bytecodecach:0,bytestr:[0,2,10],cach:[1,2,4,7,10,11],cache_s:0,cacheabl:2,calcul:[0,1,11],call:[0,1,2,4,5,6,7,9],call_binop:9,call_filt:1,call_funct:10,call_method:2,call_someth:11,call_unop:9,callabl:[0,1,2,9,11],callback:[0,1,2,9],callblock:2,caller:[1,2,9,11],can:[0,1,2,3,4,5,6,8,9,10,11,12],can_assign:2,can_edit:11,cannot:[0,1,2,11],capit:11,caption:[11,12],captur:11,care:[0,2,11],carri:[1,11],case_sensit:11,catalog:1,catch_kwarg:11,catch_vararg:11,categori:11,caught:9,caus:[0,1,3,11],ceil:[0,11],cell:12,center:11,central:[0,2],certain:[0,3,9,11],cgi:2,chain:[0,11],chang:[0,1,2,3,5,10,11],changelog:[4,7],charact:[0,2,3,11],check:[0,1,2,3,9,11],check_someth:11,checksum:0,child:[2,3,12],children:[2,11],choic:1,choiceload:0,choke:0,choos:2,chosen:[3,11],circuit:2,circumst:[1,11],citi:3,clash:[1,2],classmethod:0,clean:[0,11],clear:[0,9,11],clear_cach:0,clickabl:11,client:0,clone:6,closest:[0,11],closur:0,cmemcach:0,code:[0,1,2,3,4,5,6,8,9,10,11],code_generator_class:[0,1],codegener:1,codenam:1,coerc:11,col:11,collect:[0,11],colon:[2,3,11],color:11,column:11,columwrapp:11,com:6,combin:[0,1,2,11],come:[0,1,3],comfort:11,comma:[1,2,5,11],comment:[0,1,3,4,7],comment_end_str:0,comment_start_str:0,common:[0,1,2,3,10,11],commun:2,compar:[2,10,11],comparison:[0,1],compat:[0,1,2,4,7,10],compil:[0,1,2,3,4,6,9],compile_express:[0,1],compile_templ:0,complet:[0,1,2,11],complex:[0,2,11],complic:11,compon:0,comprehens:3,concat:2,concaten:[1,2,8,11],concept:[0,10,11],condexpr:2,condit:[1,2,3,11],config:5,configur:[0,1,2,3,4,5,9,10,11],conform:0,confus:[1,11],consequ:11,consid:[0,9,11],consist:[0,1,11],constant:[1,2,11],construct:[0,1,2,11],constructor:[0,2,11],consum:[1,10],consumpt:0,contain:[0,1,2,3,5,11],content:[1,2,11],context:[1,2,4,6,7,8,9,10],context_class:[0,1],contextfilt:0,contextfunct:[0,1,3],contextrefer:2,continu:[2,11],contrib:[0,2],control:[0,4,7],conveni:[2,11],conver:2,convers:[0,9,10,11],convert:[0,1,2,11],convolut:1,copi:[0,1,2,5,9,11],copyright:11,core:0,coroutin:0,correct:[0,1,2,3,4,11],correctli:[1,2,11],correl:1,correspond:[9,11],could:[0,1,2,11],count:[1,2,11],count_newlin:2,coupl:0,cover:[0,2,10,11],cpython:1,creat:[0,1,2,6,8,9,11],creation:2,credit:3,crucial:9,css:[3,11,12],csv:11,ctx:[0,2],ctype:3,curli:11,current:[0,2,3,11],custom:[1,2,3,4,7,9,10],cut:11,cycl:[1,11,12],cycler:[1,11],data:[0,1,2,3,6,8,11],databas:[0,1,3],date:[0,11],datetim:0,datetimeformat:0,deactiv:[0,11],dead:11,deal:[1,11],debian:1,debug:[0,1,2,3,4,11],debugg:1,debugsupport:[1,3],debugundefin:0,decemb:1,decim:[1,11],decis:3,declar:11,decod:0,decor:[0,1,9],decrement:11,deep:[1,11],deeper:0,def:[0,2,8,9,10],default_binop_t:9,default_for_str:0,default_unop_t:9,default_valu:11,defin:[0,1,2,5,8,11,12],definit:[1,2,11],deflat:0,deleg:9,delet:9,delimit:[0,2,11],depend:[0,1,3,11],depth0:11,depth:[1,11],dequ:9,deriv:1,describ:[0,2,11],descript:[5,11],design:[0,1,2,3,4,6,7],desir:[0,11,12],detail:[0,1,10,11],detect:1,determin:11,dev:3,devappserver2:3,develop:[0,1,3,11],dialog:11,dict:[0,1,2,6,9,11],dictionari:[0,2,11],dictload:0,dictsort:[1,11],did:11,differ:[0,1,2,3,10,11,12],dig:0,direct:[0,2,11],directli:[0,2,3,4,9],directori:[0,5,6],disabl:[0,1,2,9,11],disable_buff:0,disabled_extens:0,disadvantag:2,disallow:0,disappear:1,discard:[2,11],discuss:1,dispatch:[0,1],displai:[0,11],distinct:11,distinguish:12,distribut:[2,6],div:[2,11],divid:[2,11],divis:[9,11],divisiblebi:[1,11],django:[0,4,6,7,11],do_someth:[0,9],doc:10,doctyp:[11,12],document:[0,1,2,6,10,12],doe:[0,1,2,3,6,9,10,11,12],doesn:[0,2,3,8,10,11],doing:0,domain:11,don:[0,1,2,3,5,11],done:[0,1,5],dot:[0,1,11],doubl:[0,2,11],doubt:3,down:[0,4,11],download:[6,11,12],drop:[2,3,5,6],drop_needl:2,dry:11,dtd:12,due:[0,1,9,11],dummi:2,dump:[0,1,11],dump_bytecod:0,dump_us:11,dumps_funct:0,dumps_kwarg:0,dure:[0,9,10,11],dyn_arg:2,dyn_kwarg:2,dynam:[0,2,10,12],each:[0,1,2,3,9,11,12],eager:1,earlier:[1,11],easi:[1,4,5,11],easier:[0,1,3,11],easiest:11,easili:11,edg:1,edit:11,editor:5,effect:[0,3],egg:0,either:[0,1,2,3,6,11],element:[10,11],elif:[1,11],elif_:2,ellipsi:11,els:[0,1,2,10,11],else_:2,email:[3,11],emb:11,embed:[2,10,11],empti:[0,1,2,5,9,10,11],enabl:[0,1,2,9,11],enable_async:0,enable_buff:0,enabled_extens:0,encod:[0,1,5,10,11],encount:12,encourag:0,end:[0,1,2],end_token:2,endautoescap:11,endblock:[3,4,10,11,12],endcach:2,endcal:11,endfilt:11,endfor:[3,4,8,10,11,12],endian:1,endif:[0,1,10,11,12],endmacro:[0,1,3,11],endraw:11,endset:11,endswith:0,endtran:11,endwith:11,enforc:[0,1,11],engin:[0,2,3,4,5,7,11],enhanc:0,enough:1,ensur:[2,9],entir:[0,11],entiti:0,entri:[5,11],env:[0,2,8,9,10],environ:[0,1,3,4,5,6,8,9,10,11],environmentattribut:2,environmentfilt:0,environmentfunct:0,eos:2,equal:11,equalto:[1,11],equival:[1,10,11],error:[0,1,2,5,9,11],escap:[0,1,2,3,4,7],especi:[0,3,9],etc:[9,11],eval:[0,1,2],eval_ctx:[0,2],evalcontext:[0,2],evalcontextfilt:0,evalcontextfunct:0,evalcontextmodifi:[0,2],evalctx:1,evalu:[1,2,3,4,7,9,10,11,12],even:[0,1,2,3,9,10,11,12],event:0,everi:[0,2,11],everyon:3,everyth:[0,11,12],everywher:[10,11],exactli:[0,2,9,11],exampl:[0,3,4,5,6,7,9,10,11],exc:[0,2],exce:11,excel:0,except:[1,2,4,5,7,9,11],exclud:[1,2,11],execut:[0,1,2,4,9,10,11,12],exist:[0,1,2,5,9,10,11],exot:1,expand:[6,11],expect:[0,1,2,11],experienc:2,experiment:[1,4,7],explain:[10,11],explan:11,explicit:[1,3,9,10],explicit_parenthes:2,explicitli:[0,1,11],exported_var:0,expos:[0,10,11],exposur:6,expr1:2,expr2:2,expr:[0,2,11],express:[0,1,3,4,5,7,9],exprstmt:2,ext:[0,2,5],extend:[0,1,2,3,10,12],extens:[0,1,3,4,5,6,7,10],extensionattribut:2,extern:[0,10],extra:[0,1,2,3,11],extra_end_rul:2,extract:[0,1,2,5],extract_transl:2,extractor:5,face:2,fact:[0,10,11],factor:3,factori:[0,2,10],fail:[0,1,2,5,11],failur:[0,1],fall:11,fallback:[1,4,7,11],fals:[0,1,2,5,9,11,12],familiar:10,fanci:5,far:[0,3,10,11],fast:[1,4,6,7],faster:3,fastest:3,favourit:5,featur:[0,1,3,4,10,11],februari:1,feedback:6,feel:[6,11],few:[0,3,5,10,11],field:[2,11],figur:[1,2],file:[0,1,2,3,5,6,8,10,11,12],filenam:[0,2,11],files:1,filesizeformat:[1,11],filesystem:[0,1],filesystembytecodecach:0,filesystemload:[0,11],fill:11,fill_with:11,filter:[1,2,3,4,7],filter_func:0,filter_stream:2,filterblock:2,find:[0,2,4,10,11],find_al:2,find_referenced_templ:0,find_undeclared_vari:0,fine:[9,11],finer:1,finish:0,first:[0,1,2,5,11,12],first_nam:11,fit:[0,11],five:[0,11],fix:1,flag:[0,1],flask:1,flexibl:[6,11],floor:11,floordiv:[2,9],flow:11,flush:[0,1],fold:1,folder:[0,1,2,5,11],follow:[0,1,2,9,10,11],followlink:0,followsymlink:1,foo:[0,1,2,3,8,9,11],foobar:[1,11],footer:11,footprint:1,for_q:1,forceescap:11,forgot:1,forloop:10,form:[0,2,9,11],format:[0,1,2,11],format_map:1,forum:2,forward:[1,2],found:[0,2,11],four:[2,11],fourth:11,fragil:[0,11],fragment:2,fragment_cach:2,fragment_cache_prefix:2,fragmentcacheextens:2,frame:[0,1],framework:[0,1,5],free:2,free_identifi:2,french:2,frequent:[4,7],friend:1,friendli:[4,6,10],from:[0,1,2,3,4,5,7,9,11,12],from_str:[0,8,9,10],fromimport:2,front:11,frozenset:9,full:[2,11],fulli:[0,2],func:9,func_cod:9,functionload:0,fundament:[3,10],further:11,furthermor:[2,9],futur:0,gender:11,gener:[0,1,2,3,6,9,10,11],generate_async:0,generator_stop:1,genshi:[0,3],gestalt:3,get:[0,1,2,3,6,10,11],get_al:0,get_attribut:10,get_context:2,get_created_pag:10,get_event_loop:0,get_export:0,get_exported_nam:0,get_gettext_transl:2,get_latest_com:3,get_or_select_templ:0,get_sourc:0,get_templ:0,getattr:[1,2,11],getattribut:1,getitem:[1,2],getlogg:0,getmtim:0,gettext:[1,5,10,11],gibi:11,giga:11,git:6,github:6,give:[0,1,2,6,10,11],given:[0,1,2,9,10,11],global:[2,4,7,12],gnutransl:2,goe:[3,11],going:11,gone:[1,10],good:[0,2,3,5,9,11],goodby:11,googl:3,got:2,grain:1,grammar:1,greater:11,greaterthan:11,greatli:1,gretel:0,grief:1,group:[0,1,11],groupbi:[1,11],grouper:11,gteq:2,guarante:0,guess:0,guid:10,hack:3,hacker:0,had:[1,10,11],hallo:0,hand:[0,2,11],handi:0,handl:[0,1,11],happen:[0,4,7,10,11],happi:3,hard:1,hardcod:0,harder:3,harm:9,has:[0,1,2,3,6,9,10,11],hasattr:0,hash:1,hat:11,hate:3,have:[0,1,2,3,4,6,8,9,10,11,12],head:11,header:11,heavili:[3,11],height:11,hello:[0,2,6,11],help:[0,1,5],helper:[0,1,2,10,11],here:[0,1,2,5,6,10,11],hidden:11,high:[4,7],higher:[0,1],highlight:[4,5,7],hint:[0,2],hit:11,hmm:10,hold:[0,2,11],holder:0,home:6,homepag:11,hook:1,horribl:2,how:[0,1,2,4,7,9,11],howev:[0,1,2,3,6,9,10,11,12],href:[0,4,11,12],htm:0,html4:0,html:[0,3,4,5,7,9,10,12],htmljinja:5,http:11,huge:[3,11],human:[3,11],i18n:[0,1,4,5,7,10],idea:[4,5,7],identifi:[1,2,4,7,11],idiom:11,idom:0,ignor:[0,1,2,5,11,12],ignore_error:0,ignore_memcache_error:0,ignore_miss:2,illustr:11,imagin:11,immut:[0,4,7,11],immutablesandboxedenviron:9,impact:0,implement:[1,2,5,9,10],impli:0,implicit:1,implicitli:[0,10,11],importednam:2,importnam:2,imposs:[1,2],improv:[0,1,11],inact:11,includ:[0,1,2,5,10,12],inclus:[0,1,11],incoher:1,incompat:[0,1],incomplet:3,inconsist:[6,10],incorrectli:1,increas:[0,1,11],incred:5,increment:[1,11],inde:[6,11,12],indent:[0,1,11],indentfirst:11,index0:11,index:[0,1,4,9,11,12],indic:11,individu:0,inequ:11,infix:11,influenc:0,info:0,inform:[0,1,2,3,11],inherit:[0,4,7,10,12],initi:[0,1,11],inject:0,inlin:[2,11],inlinegettext:2,inner:[1,11],inner_sidebar:11,innermost:[11,12],input:11,input_field:11,insecur:9,insensit:[0,1,11],insert:9,insid:[0,1,2,11],inspir:[2,11],instal:[1,2,3,4,5,7],install_gettext_cal:2,install_gettext_transl:2,install_null_transl:2,instanc:[0,1,6,9,11],instanti:0,instead:[0,1,2,3,9,10,11,12],instruct:0,integ:[0,1,2,3,8,11],integr:[2,4,7],intellig:0,intend:1,interact:3,intercept:[1,4,7],intercepted_binop:9,intercepted_unop:9,interest:[9,11],interfac:[0,1,2,3,10],intermedi:8,intern:[0,1,2,3,6,9,10,11],internalnam:2,internation:[2,10],interpret:[1,10],introduc:[0,1,2,11],introduct:[4,7],invalid:[0,1,11],invers:0,invok:[0,11],ipsum:11,is_act:11,is_internal_attribut:9,is_prim:0,is_safe_attribut:9,is_safe_cal:9,is_undefin:0,is_up_to_d:0,isn:[4,7,11],issu:[0,1,2,3,11],item:[0,1,2,4,7,8,10,11],iter:[0,1,2,3,11],iter_child_nod:2,iter_field:2,iteritem:[0,11],iterkei:0,itervalu:0,its:[5,8],itself:[0,2,11],januari:1,japanes:3,javascript:[3,9],jinja1:[4,5,7],jinja2:[0,1,2,5,6,8,9,10,11,12],jinja:[0,2,4,5,6,7,8,9,10,11],jinja_cach:0,jinja_env:[2,5],jinjavitu:1,job:11,johansson:3,john:[0,6,11],join:[0,1,10,11],join_path:0,joiner:[1,11],json:[0,11],juli:1,june:1,just:[0,1,3,4,5,11],jython:[1,3],keep:[0,1,2,3,6,9,11],keep_trailing_newlin:[0,11],kei:[0,1,2,9,11],kenni:11,keyerror:[0,1],keyword:[0,1,2,6,11],kill:11,killword:11,kind:[0,2,11],knight:0,know:[0,3,11],knowledg:0,known:[0,1,11],kong:1,kwarg:[0,2,8,11],lack:1,lambda:[0,9],lang:11,languag:[0,2,4,6,11],larg:[0,2],largest:11,last:[0,1,2,9,11],last_nam:11,later:[0,1,2,11],latest:[0,3],latest_com:3,latex:[3,11],latter:[2,5,6],layer:[0,11],layout:[0,3,10,11,12],layout_templ:11,lead:[0,11,12],leakag:1,least:[0,2],leav:[3,11],leewai:[0,1,11],left:[0,1,2,9,11],length:[1,11],less:[2,3],lessthan:11,let:[0,9,11],letter:11,level:[1,2,4,7,11],lex:[0,2],lexer:[0,1,2],lib:6,librari:[0,1,2,5,6,10],like:[0,1,2,3,5,8,9,10,11],likewis:[0,11],limit:[0,1,2,3,11],line:[0,1,2,4,7],line_comment_prefix:0,line_statement_prefix:[0,5],linebreak:[0,1,2,11],linecount:11,lineno:[0,2],link:[0,11,12],linux:0,lipsum:11,list:[0,1,2,3,4,5,7,8,9,10,12],list_of_us:11,list_templ:0,listen:2,listx:11,liter:[0,1,2,3,8],literal_ev:8,load:[0,1,2,3,6,10,11],load_bytecod:0,load_func:0,load_templ:0,loader:[1,4,5,7,10,11],local:[0,1,2],localiz:2,locat:[0,11],log:[0,1],log_funct:0,logger:[0,1],loggingundefin:0,logic:[1,4,7],longer:[1,2,3,10,11],look:[0,1,2,4,5,7,8,10,11],lookup:[0,1,2],loop:[0,1,3,4,7],loop_item:11,loopcontrol:2,lorem:11,lost:11,lot:[0,1,2,3,11],low:[1,4,7],lower:11,lowercas:11,lstrip_block:[0,11],lteq:2,macro:[0,1,2,4,7,10],made:[1,3,11],magic:1,mai:[0,1,2,3,5,8,9,10,11],main:[0,2,11],mainli:0,maintain:3,major:2,make:[0,1,2,6,9,10,11,12],make_logging_undefin:[0,1],make_modul:0,mako:[3,4,7],malform:2,manag:3,mandatori:2,mani:[0,1,2,3,5],map:[0,1,5,11],margin:11,mark:[0,1,2,3,9,10,11],marksaf:2,marksafeifautoescap:2,markup:[0,1,2,3,11],markupsaf:[1,11],master:[4,7,11],match:[0,1,2,3,11],materi:0,math:[0,1],mathemat:1,matter:[0,3,11],max:[1,11],maximum:9,mbc:0,mean:[0,1,3,6,9,11],measur:0,mebi:11,mechan:0,mega:11,member:[0,11],memcach:[0,1,10],memcachedbytecodecach:0,memori:[0,1,10,11],menu:[4,7],mess:11,messag:[0,1,2,5,9,11],meta:[1,4,7],method:[0,1,5,6,9,11,12],might:[0,1,2,6,9,11],min:[1,11],mind:[2,3,6,9,11],minim:[0,11],minimalclientinterfac:0,minu:11,miss:[0,1,3,11],mod:[2,9],mode:[0,1,2,3,5,6,10],model:[3,4],modern:4,modif:[0,9,10],modifi:[0,1,2,3,9,11],modifies_known_mut:9,modul:[0,1,2,3,5,6,9,10,11],moduleload:[0,1],modulo:[2,11],more:[0,1,2,3,9,10,11],most:[0,1,2,3,6,9,10,11],mostli:[10,11],motiv:2,move:[2,10,11],mro:9,msg:2,mtime:0,much:[0,3,9,11],mul:[2,9],multilingu:2,multipl:[0,1,2,3,6,9,10,11],multipli:[2,11],must:[0,2,11],mutabl:9,mutablemap:9,mutablesequ:9,mutableset:9,my_dict:11,my_list:11,my_vari:11,mycach:0,mydict:11,myenviron:9,myfilt:0,myload:0,mypackag:0,mystr:11,mytempl:0,mytext:11,naiv:0,name:[0,1,2,3,6,10],name_onli:2,namespac:[1,2,4,7,11],nativ:[1,4,7,9,11],nativeenviron:[1,8],nativetempl:8,nativetyp:8,natur:0,navig:[11,12],navigation_bar:12,nbsp:11,neat:12,necessari:[1,9,10,11],necessarili:0,need:[0,2,3,5,6,9,11],needl:2,neg:[2,9],negat:[2,11],neither:[0,3,11],nest:1,never:[3,11],new_context:0,newer:[0,1,11],newlin:[0,1,2,11],newline_sequ:0,newstyl:[1,11],next:[0,1,2,11,12],next_if:2,nextitem:[1,11],ngettext:[2,11],nicer:[0,1],nih:0,nl2br:0,no_condexpr:2,node:[0,1,2,8],node_typ:2,nofollow:[0,11],non:[0,1,2,5,9,11],none:[0,2,9,11],noniterableundefin:0,noop:2,noopen:[0,1],nor:[0,3,10,11],normal:[0,10,11],notabl:[10,11],notat:[1,11],note:[4,6,7],noth:[0,11],notic:[1,3,6],notin:2,notrim:11,novemb:1,now:[0,1,2,9,10,11],nsref:2,nulltransl:2,nullundefin:0,num:[1,2,11],number:[0,1,2,3,4,8,11],nutshel:11,obj:[0,9,11],object:[0,1,2,3,5,6,8,9,10,12],occur:[0,1,9],occurr:11,octob:1,odd:[1,10,11,12],often:[2,3,5,11,12],okai:11,old:[0,1,2,10,11],older:[0,1,2,3,6,11],omit:[0,3,11],onc:[0,2,5,9],one:[0,1,2,3,5,9,10,11,12],ones:[3,9],onli:[0,1,2,3,8,9,10,11,12],onward:[5,9,11],opaqu:0,opcod:1,open:[0,11],oper:[0,1,2,3,4,7,10],operand:[2,11],ops:2,optim:[0,1,2,4],option:[0,1,2,4,5,8,9,10,11],order:[0,1,9,11],order_bi:3,ordereddict:11,ordinari:0,origin:[0,1],other:[0,1,2,3,4,5,6,7,9],otherwis:[0,2,8,11],our:[1,2],out:[0,1,2,10,11,12],outdat:0,outer:[1,11,12],outer_loop:11,outermost:2,outliv:11,output:[0,1,2,10,11],outsid:[8,11,12],over:[0,1,2,3,11],overlai:[0,1,2],overlayscop:[1,2],overrid:[0,1,2,4,7,9,10],overridden:[0,4,7,9],overriden:1,oversight:1,overview:0,overwrot:1,own:[0,11],owner:0,packag:[0,1,6],package_nam:0,package_path:0,packageload:[0,5,6],page:[3,4,6,10,11,12],page_detail:11,pai:0,pair:[2,11],pairwis:11,pallet:6,paragraph:[0,11],param:2,paramet:[0,1,2,3,11],parent:[0,3,4,7,10,11],parenthes:[1,2,10,11],pars:[0,2,8],parse_assign_target:2,parse_express:2,parse_stat:2,parse_tupl:2,parser:1,part:[0,1,2,5,11,12],partial:1,particular:[0,1,11],pass:[0,1,2,3,5,6,8,9,10,11],password:11,past:[0,1,10,11],path:[0,2,5],pattern:0,penalti:0,peopl:[1,5],per:[0,1,2,5,9,11,12],perfect:9,perfectli:0,perform:[0,1,2,3,9,10,11],permit:9,person:11,php:11,pick:0,piec:[0,9,11],pip:6,pipe:11,place:[0,1,11],placehold:[2,11],plain:11,pleas:[3,6,11],plu:[0,11],plugin:5,plural:[1,11],pluraliz:11,point:[0,2,4,5,11,12],polici:[1,2,4,7],port:1,pos:9,posit:[1,2,11],possibl:[0,1,2,3,9,10,11,12],post:11,pow:[2,9],power:[2,4,5,9,10,11],pprint:11,preced:[1,11],precis:11,precompil:[0,1],prefer:[0,2,6,11],prefix:[0,1,2,3,11],prefixload:0,prepar:2,prepend:11,preprocess:[0,1,2],prerequisit:[4,7],present:[0,11],preserv:[0,1,11],pretti:[0,3,10,11],prevent:[1,4],previou:[0,1,11],previous:[1,10,11],previtem:[1,11],price:11,primari:[0,3],prime:0,principl:6,print:[0,2,3,8,11,12],prioriti:1,privat:[9,11],probabl:[0,11],problem:[0,1,2,3,11],problemat:0,process:[0,2,3,11],produc:[1,8],product:3,program:11,progress:11,prohibit:9,project:5,prone:[2,11],pronunci:3,propag:[1,5,11],properli:[1,2],properti:11,protect:1,provid:[0,1,2,3,5,6,10,11],pub_dat:[0,3],pull:1,pure:1,purpos:[0,3,6,11],push:2,put:[0,4,7,11,12],py_compil:[0,1],pyc:0,pylon:[0,4,7],pypi:[0,1],python2:6,python:[0,1,2,4,7,9,10,11],queri:[1,3],question:[4,7],quick:3,quot:[1,11],qux:11,rais:[0,1,2,9,11],random:[1,11],randomli:5,rang:[8,11],raquo:0,rare:[0,1,11],rather:[0,1,3,11],raw:11,rdfa:11,reach:[2,11],react:0,read:[0,1,11],readabl:[0,3,11],real:[0,11],realli:[3,11,12],realnam:11,reason:[0,2,3,11],reassign:2,rebind:11,rebuild:0,receiv:[0,11],recent:[0,6,9],recommend:[0,3,6,9],recompil:0,reconfigur:[0,11],recreat:0,recurs:[1,2,11],redhat:1,reduc:[0,1],refer:[0,1,2,11],referenc:[0,11],reflect:3,regardless:11,regist:[0,1],regress:1,regular:[0,1,2,9,10,11],reject:[0,1,11],rejectattr:[1,11],rel:[0,1,11,12],relat:[0,2,3,5],releas:1,relev:1,reli:[0,11],reload:[0,1],remain:[1,11],remaind:11,remov:[0,1,2,3,11],renam:[1,3,11],render:[0,1,2,5,6,8,9,11,12],render_async:0,render_box:11,render_dialog:11,render_jinja:5,rendertempl:10,repeat:11,replac:[0,1,3,11],repli:11,report:1,repr:[1,2],repres:[0,2,11],represent:[0,2,10,11],request:[0,1,2,11],requir:[0,1,2,3,10,11],reset:[0,2,11],resolv:[0,1],resourc:[0,9],respect:11,respons:[0,11],rest:2,restor:[0,1,3],restrict:[1,3],result:[0,1,2,8,11],retain:11,retriev:3,reusabl:[2,11],revers:[1,11],revert:[1,2,11],revindex0:11,revindex:11,rewrit:[0,11],right:[2,6,9,11],risk:11,root:[0,5],root_render_func:0,roughli:0,rougli:0,round:11,row:[4,7,11],row_class:11,rowloop:12,rule:[0,1,11],run:[0,1,9,10],runtim:[0,1,2,6,9],safe:[0,1,2,3,9,11],safeti:[3,11],sagen:0,sai:[0,11],said:11,sake:11,salt:3,same:[0,1,2,3,9,10,11],samea:11,sandbox:[0,1,3,4,7,10],sandboxedenviron:[0,1,9,10],save:0,scene:0,scope:[0,1,2,3],scopedevalcontextmodifi:[0,2],script:[1,5,11],search:[1,4],searchpath:0,second:[0,1,2,11],section:[1,2,5,6,10,11],secur:[0,1,4,6,9],securityerror:[0,9],see:[0,1,2,6,10,11],seem:3,segfault:1,select:[0,1,11],select_autoescap:[0,1],select_templ:0,selectattr:[1,11],self:[0,2,8,9,11],semant:[1,10,11],sens:[0,11,12],sensibl:0,sensit:11,sep:11,separ:[0,1,3,5,11],septemb:1,seq:11,sequenc:[0,1,11],sequenti:11,seriou:3,server:[3,9],server_softwar:3,set:[0,1,2,3,5,9,11,12],set_ctx:2,set_environ:2,set_lineno:2,setup:[0,1,6],setuptool:6,sgml:11,share:[0,3,9],shine:0,ship:3,shortcut:2,shorten:11,should:[0,1,2,3,6,9,10,11],show:[2,3,9,10,11,12],shown:6,sick:11,side:[0,1,3,11],sidebar:[2,11],sign:[1,11],silenc:1,silent:[0,1,5],similar:[0,1,3,10,11],similarli:[0,10,11],simpl:[0,2,11,12],simplecach:2,simpler:10,simplest:[0,11],simpli:11,simplifi:[1,2],sinc:[0,1,3,5,11],singl:[0,2,8,11],singleton:[10,11],singular:11,site:[6,11],sitemap:11,situat:[0,1,3,11],six:1,size:[0,1,11],skeleton:[11,12],skip:[1,2,11],skip_if:2,slash:[0,1,11],slice:[2,11],slightli:[0,1,11],slow:0,slower:9,small:[0,1,6,10,11],smaller:1,smallest:11,smarti:6,snippet:[3,5,11],softwar:2,solidu:11,solut:9,solv:[1,2],some:[0,1,2,3,5,9,10,11,12],some_nam:0,someth:[0,1,2,4,5,7,8,9,11],sometim:[0,11],somewher:0,soon:0,sort:[0,1,9,11],sort_kei:0,sound:[2,11],sourc:[0,1,2,3,6,11],sourcecod:[0,3,11],space:[0,11],span:11,speak:[3,11],special:[0,1,2,9,10,11,12],special_sidebar:11,specif:[0,1,2,9,11],specifi:[0,2,9,11],speedup:1,split:[0,11],spot:1,sqrt:0,stack:10,stage:0,stai:2,stand:1,standalon:12,standard:[0,2,11],start:[0,1,2,9,11],startswith:3,state:[0,2],statement:[0,1,4,7],statist:3,statu:0,step:[2,6,8,11],stick:6,still:[0,1,3,6],stmt:2,stop:[2,3,11],stopiter:[0,1],storag:[0,2,10],store:[0,2,11],str:[0,1,8,9,11],stream:[0,1,2],strftime:0,strict:[0,5],strict_c:5,strictundefin:0,string:[0,1,2,3,5,6,8,10,11,12],strip:[0,1,11],striptag:[0,11],strong:0,strongli:9,structur:[4,7],stupid:3,style:[0,1,11,12],stylesheet:[11,12],sub:[2,9],subclass:[0,1,9],subdirectori:11,submenu:11,subscrib:1,subscript:[1,2,11],subset:[3,10],substr:11,subtract:[1,2,11],succeed:11,suddenli:1,sum:[1,11],sume:11,support:[1,2,4,5,7,9,10,11,12],suppos:2,sure:[0,2,6,9,10],surpris:[0,12],surround:[0,1,2,11],symbol:[0,9,11],sync:0,synopsi:[4,7],syntact:10,syntax:[0,1,2,3,4,5,6,8,10,11],sys:0,system:[0,1,2,3,4,6,10,11],tab:[0,11],tabl:[3,9,11,12],tag:[0,1,2,3,5,10,12],taint:11,take:[0,1,11,12],taken:[2,3],target:[0,1,2,11],task:2,techniqu:0,tell:[0,5,9,11],temp:0,templ:3,templat:[0,1,2,4,5,6,7,8,9,12],template_class:0,template_nam:0,template_name_or_list:0,templateassertionerror:0,templatedata:2,templateerror:0,templatenotfound:0,templateruntimeerror:0,templatesnotfound:0,templatestream:[0,1],templatesyntaxerror:[0,2],temporari:0,temporarili:0,term:[10,11],termin:11,terribl:[2,4,7],test:[1,2,3,4,7,9],test_ani:2,testsuit:[3,5],text:[0,5,6,8,10,11,12],text_typ:0,textarea:11,textmat:[4,7],than:[0,1,3,9,10,11],thei:[0,1,2,3,9,10,11],them:[0,2,9,10,11],thi:[0,1,2,3,5,6,8,9,10,11,12],thing:[0,1,2,3,11],third:11,thoma:3,those:[0,2,11],though:[0,1,3],thread:0,threat:2,three:[0,11],through:[0,1,6,11],thu:[10,11],time:[0,1,2,3,4,9,11,12],timeout:[0,2],tini:11,tip:[4,7],titl:[1,4,10,11,12],titlecas:11,tmp:0,tmpl:3,togeth:11,toggl:1,tojson:[0,1,11],token:[0,1,2],token_typ:[0,2],token_valu:2,tokenstream:2,toler:11,ton:3,too:[0,1,2,10,11],took:[3,11],tool:[2,3,5,11],top:[1,11],topic:0,toplevel:1,total:[0,1,11],trac:2,traceback:[0,1,4,7,9],track:0,tracker:6,tradit:8,tradition:0,trail:[0,1,11],tran:[0,1,2,5,11],transit:12,translat:[1,2,9,10,11],transpar:1,treat:[0,1,11],tree:[0,2],tri:[0,3,9],trick:[4,7,11],trigger:2,trim:[0,1,11],trim_block:[0,11],trim_url_limit:11,trivial:2,troubl:2,truediv:9,truli:0,truncat:[0,1,2,11],trust:11,truthi:11,tummi:0,tune:9,tupl:[0,1,2,11],turn:[0,1],two:[0,1,2,5,8,11],txt:0,type:[1,2,4,5,7,9,10,11,12],typecheck:0,typeerror:0,uganda:3,ugettext:[1,2],ugli:11,unabl:[0,2,3],unari:[1,2,9],unaryexpr:2,unavail:[3,9,11],unbound:[1,11],unbuff:0,unchang:[0,11],uncommon:3,unconsum:11,und:0,undeclar:0,undefin:[1,4,5,7,9,11],undefined_to_non:0,undefinederror:0,under:[0,1],underli:[0,1],underscor:[2,9,11],understand:[0,11],undocu:1,unescap:0,unfortun:0,ungettext:2,unicod:[1,2,3,4,6,7,9,10,11],unifi:0,uninstal:2,uninstall_gettext_transl:2,unintend:[1,11],uniqu:[0,1,11],unittest:[0,6],unix:[0,1],unknown:1,unless:[0,9,11],unlik:[0,1,11],unlimit:12,unload:0,unmarshal:1,unmodifi:3,unnam:2,unop_t:9,unoptim:[1,2],unpack:[2,6,11],unsaf:[0,2,3,9,11],unsafe_cal:9,unsort:11,unsupport:9,unsur:6,until:[0,2,5,11],untrust:[1,9,11],unus:1,upcom:3,updat:0,upgrad:1,upper:[9,11],uppercas:[1,11],uptod:0,uptodatefunc:0,url:[1,4,11],urlencod:[1,11],urliz:[0,1,11],usag:[0,1,2,4,7,10,11],use:[0,1,2,3,5,6,8,9,10,11,12],used:[0,1,2,3,4,5,9,10,11,12],useful:[0,2,6,8,9,11],user:[0,1,2,4,8,9,10,11],user_count:11,user_id:10,userdict:9,usernam:[4,10,11],uses:[0,1,2,3,10,11],using:[0,1,2,3,4,5,6,8,9,10,11],usr:6,usual:[0,2,3,11,12],utf:[0,1,5,11],util:[2,4,7],val:11,valid:[0,2,11],valu:[0,1,2,5,6,8,9,11],valueerror:11,vararg:11,variabl:[0,1,2,3,4,7,10,12],variable_end_str:0,variable_start_str:0,variou:[0,1,11],verbos:[10,11],veri:[0,10,11,12],version:[0,2,3,4,5,7,9,11],versu:0,via:[0,1,5,9],view:[0,3],vim:[4,7],visibl:[1,3,11],visit:12,volatil:0,w3c:12,wai:[0,1,2,3,6,11],want:[0,1,2,3,5,10,11,12],warn:1,wasn:0,weakref:1,web:[0,2,3,9],webpag:11,websit:0,weird:[4,7],welcom:11,well:[0,1,2,5,9,11],went:1,were:[0,1,2,5,10,11],werkzeug:[0,2],what:[0,1,2,4,5,6,7,9,10,11],when:[0,1,2,3,6,11],whenev:[0,11],where:[0,1,2,8,11],whether:[1,11],which:[0,1,2,3,6,10,11,12],whitelist:[3,9],whitespac:[0,1,4,7,12],who:0,whole:[0,11],why:[0,2,4,7],wide:[0,4],width:11,window:0,wish:6,with_:2,with_condexpr:2,with_context:2,with_namespac:2,with_tupl:2,within:[0,11],without:[0,1,2,3,11],won:[3,9,10],word:[0,11],wordcount:11,wordwrap:[1,11],work:[0,1,2,3,6,9,10],workaround:3,world:[0,2,11],would:[0,1,2,3,5,9,10,11],wouldn:11,wrap:[2,11],wrapper:2,wrapstr:11,write:[0,1,3,4,7,11],write_bytecod:0,written:[0,6,11],wrong:1,wrote:11,wsgi:0,xbb:0,xf6:0,xhtml:0,xml:[0,3,11],xmlattr:11,xrang:0,xss:[3,4],yai:11,yes:0,yet:[0,2],yield:[0,2,11],you:[0,1,2,3,4,5,6,8,9,10,11,12],your:[0,3,5,6,8,11],yourappl:[0,5],yourself:[0,2,6,10,11],zero:1,zip:[0,1],zipfil:0},titles:["API","Jinja Changelog","Extensions","Frequently Asked Questions","Welcome to Jinja2","Integration","Introduction","Jinja2 Documentation","Native Python Types","Sandbox","Switching from other Template Engines","Template Designer Documentation","Tips and Tricks"],titleterms:{"0rc1":1,"default":3,"function":11,"import":11,"null":12,"super":11,"switch":10,Adding:2,For:11,The:0,With:[2,11],access:12,activ:12,addit:[4,7],altern:12,api:[0,2,6,8,9,10],argument:10,ask:3,assign:11,ast:2,async:0,autoescap:[0,2,3,11],automat:11,babel:5,base:11,basic:[0,6],behavior:11,block:11,builtin:11,bytecod:0,cach:0,call:[3,10,11],changelog:1,child:11,comment:11,comparison:11,compat:3,context:[0,3,11],control:[2,11],custom:0,cycl:10,depend:6,design:11,develop:6,django:[3,10],document:[4,7,11],easy_instal:6,egg:6,end:11,engin:10,environ:2,escap:11,evalu:0,exampl:[2,8],except:0,experiment:6,express:[2,11],extend:11,extens:[2,11],fallback:12,fast:3,filter:[0,10,11],frequent:3,from:[6,10],gettext:2,global:[0,11],happen:3,high:0,highlight:12,how:3,html:11,i18n:[2,11],idea:3,identifi:0,immut:3,implement:[0,11],includ:11,inform:[4,7],inherit:11,instal:6,integr:5,intercept:9,introduct:6,isn:3,item:12,jinja1:10,jinja2:[3,4,7],jinja:[1,3],level:0,line:11,list:11,liter:11,loader:0,logic:[3,11],look:3,loop:[2,10,11,12],low:0,macro:[3,11],mako:10,manual:11,markupsaf:6,master:12,math:11,menu:12,meta:0,method:[2,10],name:11,namespac:0,nativ:8,nest:11,newstyl:2,note:[0,9,11],object:11,oper:[9,11],other:[10,11],overrid:11,overridden:3,parent:12,parser:2,polici:0,prerequisit:6,put:3,pylon:5,python:[3,6,8],question:3,releas:6,row:12,sandbox:9,scope:11,someth:3,statement:[2,11],structur:11,support:[0,3,6],synopsi:11,tag:11,tarbal:6,templat:[3,10,11],terribl:3,test:[0,10,11],textmat:5,tip:12,traceback:3,trick:12,trim:2,type:[0,8],undefin:0,unicod:0,usag:6,util:0,variabl:11,version:[1,6],via:6,vim:5,weird:3,welcom:4,what:3,whitespac:[2,11],why:3,work:11,write:2}})PKê|>]FÏ^þ‰R‰Rhtml/switching.htmlnu„[µü¤ Switching from other Template Engines — Jinja2 2.10.1 documentation

    Switching from other Template Engines¶

    If you have used a different template engine in the past and want to switch to Jinja2 here is a small guide that shows the basic syntactic and semantic changes between some common, similar text template engines for Python.

    Jinja1¶

    Jinja2 is mostly compatible with Jinja1 in terms of API usage and template syntax. The differences between Jinja1 and 2 are explained in the following list.

    API¶

    Loaders
    Jinja2 uses a different loader API. Because the internal representation of templates changed there is no longer support for external caching systems such as memcached. The memory consumed by templates is comparable with regular Python modules now and external caching doesn’t give any advantage. If you have used a custom loader in the past have a look at the new loader API.
    Loading templates from strings
    In the past it was possible to generate templates from a string with the default environment configuration by using jinja.from_string. Jinja2 provides a Template class that can be used to do the same, but with optional additional configuration.
    Automatic unicode conversion
    Jinja1 performed automatic conversion of bytestrings in a given encoding into unicode objects. This conversion is no longer implemented as it was inconsistent as most libraries are using the regular Python ASCII bytestring to Unicode conversion. An application powered by Jinja2 has to use unicode internally everywhere or make sure that Jinja2 only gets unicode strings passed.
    i18n
    Jinja1 used custom translators for internationalization. i18n is now available as Jinja2 extension and uses a simpler, more gettext friendly interface and has support for babel. For more details see i18n Extension.
    Internal methods
    Jinja1 exposed a few internal methods on the environment object such as call_function, get_attribute and others. While they were marked as being an internal method it was possible to override them. Jinja2 doesn’t have equivalent methods.
    Sandbox
    Jinja1 was running sandbox mode by default. Few applications actually used that feature so it became optional in Jinja2. For more details about the sandboxed execution see SandboxedEnvironment.
    Context
    Jinja1 had a stacked context as storage for variables passed to the environment. In Jinja2 a similar object exists but it doesn’t allow modifications nor is it a singleton. As inheritance is dynamic now multiple context objects may exist during template evaluation.
    Filters and Tests
    Filters and tests are regular functions now. It’s no longer necessary and allowed to use factory functions.

    Templates¶

    Jinja2 has mostly the same syntax as Jinja1. What’s different is that macros require parentheses around the argument list now.

    Additionally Jinja2 allows dynamic inheritance now and dynamic includes. The old helper function rendertemplate is gone now, include can be used instead. Includes no longer import macros and variable assignments, for that the new import tag is used. This concept is explained in the Import documentation.

    Another small change happened in the for-tag. The special loop variable doesn’t have a parent attribute, instead you have to alias the loop yourself. See Accessing the parent Loop for more details.

    Django¶

    If you have previously worked with Django templates, you should find Jinja2 very familiar. In fact, most of the syntax elements look and work the same.

    However, Jinja2 provides some more syntax elements covered in the documentation and some work a bit different.

    This section covers the template changes. As the API is fundamentally different we won’t cover it here.

    Method Calls¶

    In Django method calls work implicitly, while Jinja requires the explicit Python syntax. Thus this Django code:

    {% for page in user.get_created_pages %}
        ...
    {% endfor %}
    

    …looks like this in Jinja:

    {% for page in user.get_created_pages() %}
        ...
    {% endfor %}
    

    This allows you to pass variables to the method, which is not possible in Django. This syntax is also used for macros.

    Filter Arguments¶

    Jinja2 provides more than one argument for filters. Also the syntax for argument passing is different. A template that looks like this in Django:

    {{ items|join:", " }}
    

    looks like this in Jinja2:

    {{ items|join(', ') }}
    

    It is a bit more verbose, but it allows different types of arguments - including variables - and more than one of them.

    Tests¶

    In addition to filters there also are tests you can perform using the is operator. Here are some examples:

    {% if user.user_id is odd %}
        {{ user.username|e }} is odd
    {% else %}
        hmm. {{ user.username|e }} looks pretty normal
    {% endif %}
    

    Loops¶

    For loops work very similarly to Django, but notably the Jinja2 special variable for the loop context is called loop, not forloop as in Django.

    In addition, the Django empty argument is called else in Jinja2. For example, the Django template:

    {% for item in items %}
        {{ item }}
    {% empty %}
        No items!
    {% endfor %}
    

    …looks like this in Jinja2:

    {% for item in items %}
        {{ item }}
    {% else %}
        No items!
    {% endfor %}
    

    Cycle¶

    The {% cycle %} tag does not exist in Jinja2; however, you can achieve the same output by using the cycle method on the loop context special variable.

    The following Django template:

    {% for user in users %}
        <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>
    {% endfor %}
    

    …looks like this in Jinja2:

    {% for user in users %}
        <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>
    {% endfor %}
    

    There is no equivalent of {% cycle ... as variable %}.

    Mako¶

    If you have used Mako so far and want to switch to Jinja2 you can configure Jinja2 to look more like Mako:

    env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')
    

    With an environment configured like that, Jinja2 should be able to interpret a small subset of Mako templates. Jinja2 does not support embedded Python code, so you would have to move that out of the template. The syntax for defs (which are called macros in Jinja2) and template inheritance is different too. The following Mako template:

    <%inherit file="layout.html" />
    <%def name="title()">Page Title</%def>
    <ul>
    % for item in list:
        <li>${item}</li>
    % endfor
    </ul>
    

    Looks like this in Jinja2 with the above configuration:

    <% extends "layout.html" %>
    <% block title %>Page Title<% endblock %>
    <% block body %>
    <ul>
    % for item in list:
        <li>${item}</li>
    % endfor
    </ul>
    <% endblock %>
    
    PKê|>]Ð40tßGßGhtml/templates.htmlnu„[µü¤ Template Designer Documentation — Jinja2 2.10.1 documentation

    Template Designer Documentation¶

    This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible, the configuration from the application can be slightly different from the code presented here in terms of delimiters and behavior of undefined values.

    Synopsis¶

    A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn’t need to have a specific extension: .html, .xml, or any other extension is just fine.

    A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template. The template syntax is heavily inspired by Django and Python.

    Below is a minimal template that illustrates a few basics using the default Jinja configuration. We will cover the details later in this document:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>My Webpage</title>
    </head>
    <body>
        <ul id="navigation">
        {% for item in navigation %}
            <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
        {% endfor %}
        </ul>
    
        <h1>My Webpage</h1>
        {{ a_variable }}
    
        {# a comment #}
    </body>
    </html>
    

    The following example shows the default configuration settings. An application developer can change the syntax configuration from {% foo %} to <% foo %>, or something similar.

    There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:

    Variables¶

    Template variables are defined by the context dictionary passed to the template.

    You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable.

    You can use a dot (.) to access attributes of a variable in addition to the standard Python __getitem__ “subscript� syntax ([]).

    The following lines do the same thing:

    {{ foo.bar }}
    {{ foo['bar'] }}
    

    It’s important to know that the outer double-curly braces are not part of the variable, but the print statement. If you access variables inside tags don’t put the braces around them.

    If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated over, and to fail for every other operation.

    Implementation

    For the sake of convenience, foo.bar in Jinja2 does the following things on the Python layer:

    • check for an attribute called bar on foo (getattr(foo, 'bar'))
    • if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))
    • if there is not, return an undefined object.

    foo['bar'] works mostly the same with a small difference in sequence:

    • check for an item 'bar' in foo. (foo.__getitem__('bar'))
    • if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))
    • if there is not, return an undefined object.

    This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks up attributes.

    Filters¶

    Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

    For example, {{ name|striptags|title }} will remove all HTML Tags from variable name and title-case the output (title(striptags(name))).

    Filters that accept arguments have parentheses around the arguments, just like a function call. For example: {{ listx|join(', ') }} will join a list with commas (str.join(', ', listx)).

    The List of Builtin Filters below describes all the builtin filters.

    Tests¶

    Beside filters, there are also so-called “tests� available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out if a variable is defined, you can do name is defined, which will then return true or false depending on whether name is defined in the current template context.

    Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:

    {% if loop.index is divisibleby 3 %}
    {% if loop.index is divisibleby(3) %}
    

    The List of Builtin Tests below describes all the builtin tests.

    Comments¶

    To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #}. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:

    {# note: commented-out template because we no longer use this
        {% for user in users %}
            ...
        {% endfor %}
    #}
    

    Whitespace Control¶

    In the default configuration:

    • a single trailing newline is stripped if present
    • other whitespace (spaces, tabs, newlines etc.) is returned unchanged

    If an application configures Jinja to trim_blocks, the first newline after a template tag is removed automatically (like in PHP). The lstrip_blocks option can also be set to strip tabs and spaces from the beginning of a line to the start of a block. (Nothing will be stripped if there are other characters before the start of the block.)

    With both trim_blocks and lstrip_blocks enabled, you can put block tags on their own lines, and the entire block line will be removed when rendered, preserving the whitespace of the contents. For example, without the trim_blocks and lstrip_blocks options, this template:

    <div>
        {% if True %}
            yay
        {% endif %}
    </div>
    

    gets rendered with blank lines inside the div:

    <div>
    
            yay
    
    </div>
    

    But with both trim_blocks and lstrip_blocks enabled, the template block lines are removed and other whitespace is preserved:

    <div>
            yay
    </div>
    

    You can manually disable the lstrip_blocks behavior by putting a plus sign (+) at the start of a block:

    <div>
            {%+ if something %}yay{% endif %}
    </div>
    

    You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:

    {% for item in seq -%}
        {{ item }}
    {%- endfor %}
    

    This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9, the output would be 123456789.

    If Line Statements are enabled, they strip leading whitespace automatically up to the beginning of the line.

    By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.

    Note

    You must not add whitespace between the tag and the minus sign.

    valid:

    {%- if foo -%}...{% endif %}
    

    invalid:

    {% - if foo - %}...{% endif %}
    

    Escaping¶

    It is sometimes desirable – even necessary – to have Jinja ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you have to use a trick.

    The easiest way to output a literal variable delimiter ({{) is by using a variable expression:

    {{ '{{' }}
    

    For bigger sections, it makes sense to mark a block raw. For example, to include example Jinja syntax in a template, you can use this snippet:

    {% raw %}
        <ul>
        {% for item in seq %}
            <li>{{ item }}</li>
        {% endfor %}
        </ul>
    {% endraw %}
    

    Line Statements¶

    If line statements are enabled by the application, it’s possible to mark a line as a statement. For example, if the line statement prefix is configured to #, the following two examples are equivalent:

    <ul>
    # for item in seq
        <li>{{ item }}</li>
    # endfor
    </ul>
    
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
    

    The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability, statements that start a block (such as for, if, elif etc.) may end with a colon:

    # for item in seq:
        ...
    # endfor
    

    Note

    Line statements can span multiple lines if there are open parentheses, braces or brackets:

    <ul>
    # for href, caption in [('index.html', 'Index'),
                            ('about.html', 'About')]:
        <li><a href="{{ href }}">{{ caption }}</a></li>
    # endfor
    </ul>
    

    Since Jinja 2.2, line-based comments are available as well. For example, if the line-comment prefix is configured to be ##, everything from ## to the end of the line is ignored (excluding the newline sign):

    # for item in seq:
        <li>{{ item }}</li>     ## this comment is ignored
    # endfor
    

    Template Inheritance¶

    The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton� template that contains all the common elements of your site and defines blocks that child templates can override.

    Sounds complicated but is very basic. It’s easiest to understand it by starting with an example.

    Base Template¶

    This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child� templates to fill the empty blocks with content:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        {% block head %}
        <link rel="stylesheet" href="style.css" />
        <title>{% block title %}{% endblock %} - My Webpage</title>
        {% endblock %}
    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}
            &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
    </html>
    

    In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those placeholders in the template.

    Child Template¶

    A child template might look like this:

    {% extends "base.html" %}
    {% block title %}Index{% endblock %}
    {% block head %}
        {{ super() }}
        <style type="text/css">
            .important { color: #336699; }
        </style>
    {% endblock %}
    {% block content %}
        <h1>Index</h1>
        <p class="important">
          Welcome to my awesome homepage.
        </p>
    {% endblock %}
    

    The {% extends %} tag is the key here. It tells the template engine that this template “extends� another template. When the template system evaluates this template, it first locates the parent. The extends tag should be the first tag in the template. Everything before it is printed out normally and may cause confusion. For details about this behavior and how to take advantage of it, see Null-Master Fallback.

    The filename of the template depends on the template loader. For example, the FileSystemLoader allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash:

    {% extends "layout/default.html" %}
    

    But this behavior can depend on the application embedding Jinja. Note that since the child template doesn’t define the footer block, the value from the parent template is used instead.

    You can’t define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in “both� directions. That is, a block tag doesn’t just provide a placeholder to fill - it also defines the content that fills the placeholder in the parent. If there were two similarly-named {% block %} tags in a template, that template’s parent wouldn’t know which one of the blocks’ content to use.

    If you want to print a block multiple times, you can, however, use the special self variable and call the block with that name:

    <title>{% block title %}{% endblock %}</title>
    <h1>{{ self.title() }}</h1>
    {% block body %}{% endblock %}
    

    Super Blocks¶

    It’s possible to render the contents of the parent block by calling super. This gives back the results of the parent block:

    {% block sidebar %}
        <h3>Table Of Contents</h3>
        ...
        {{ super() }}
    {% endblock %}
    

    Named Block End-Tags¶

    Jinja2 allows you to put the name of the block after the end tag for better readability:

    {% block sidebar %}
        {% block inner_sidebar %}
            ...
        {% endblock inner_sidebar %}
    {% endblock sidebar %}
    

    However, the name after the endblock word must match the block name.

    Block Nesting and Scope¶

    Blocks can be nested for more complex layouts. However, per default blocks may not access variables from outer scopes:

    {% for item in seq %}
        <li>{% block loop_item %}{{ item }}{% endblock %}</li>
    {% endfor %}
    

    This example would output empty <li> items because item is unavailable inside the block. The reason for this is that if the block is replaced by a child template, a variable would appear that was not defined in the block or passed to the context.

    Starting with Jinja 2.2, you can explicitly specify that variables are available in a block by setting the block to “scoped� by adding the scoped modifier to a block declaration:

    {% for item in seq %}
        <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
    {% endfor %}
    

    When overriding a block, the scoped modifier does not have to be provided.

    Template Objects¶

    Changed in version 2.4.

    If a template object was passed in the template context, you can extend from that object as well. Assuming the calling code passes a layout template as layout_template to the environment, this code works:

    {% extends layout_template %}
    

    Previously, the layout_template variable had to be a string with the layout template’s filename for this to work.

    HTML Escaping¶

    When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches:

    1. manually escaping each variable; or
    2. automatically escaping everything by default.

    Jinja supports both. What is used depends on the application configuration. The default configuration is no automatic escaping; for various reasons:

    • Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include HTML (e.g. numbers, booleans) which can be a huge performance hit.
    • The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values, the return value is double-escaped HTML.

    Working with Manual Escaping¶

    If manual escaping is enabled, it’s your responsibility to escape variables if needed. What to escape? If you have a variable that may include any of the following chars (>, <, &, or ") you SHOULD escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter:

    {{ user.username|e }}
    

    Working with Automatic Escaping¶

    When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe. Variables and expressions can be marked as safe either in:

    1. the context dictionary by the application with MarkupSafe.Markup, or
    2. the template, with the |safe filter

    The main problem with this approach is that Python itself doesn’t have the concept of tainted values; so whether a value is safe or unsafe can get lost.

    If a value is not marked safe, auto-escaping will take place; which means that you could end up with double-escaped contents. Double-escaping is easy to avoid, however: just rely on the tools Jinja2 provides and don’t use builtin Python constructs such as str.format or the string modulo operator (%).

    Jinja2 functions (macros, super, self.BLOCKNAME) always return template data that is marked as safe.

    String literals in templates with automatic escaping are considered unsafe because native Python strings (str, unicode, basestring) are not MarkupSafe.Markup strings with an __html__ attribute.

    List of Control Structures¶

    A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %} blocks.

    For¶

    Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

    <h1>Members</h1>
    <ul>
    {% for user in users %}
      <li>{{ user.username|e }}</li>
    {% endfor %}
    </ul>
    

    As variables in templates retain their object properties, it is possible to iterate over containers like dict:

    <dl>
    {% for key, value in my_dict.iteritems() %}
        <dt>{{ key|e }}</dt>
        <dd>{{ value|e }}</dd>
    {% endfor %}
    </dl>
    

    Note, however, that Python dicts are not ordered; so you might want to either pass a sorted list of tuple s – or a collections.OrderedDict – to the template, or use the dictsort filter.

    Inside of a for-loop block, you can access some special variables:

    Variable Description
    loop.index The current iteration of the loop. (1 indexed)
    loop.index0 The current iteration of the loop. (0 indexed)
    loop.revindex The number of iterations from the end of the loop (1 indexed)
    loop.revindex0 The number of iterations from the end of the loop (0 indexed)
    loop.first True if first iteration.
    loop.last True if last iteration.
    loop.length The number of items in the sequence.
    loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
    loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
    loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
    loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
    loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
    loop.changed(*val) True if previously called with a different value (or not called at all).

    Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:

    {% for row in rows %}
        <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
    {% endfor %}
    

    Since Jinja 2.1, an extra cycle helper exists that allows loop-unbound cycling. For more information, have a look at the List of Global Functions.

    Unlike in Python, it’s not possible to break or continue in a loop. You can, however, filter the sequence during iteration, which allows you to skip items. The following example skips all the users which are hidden:

    {% for user in users if not user.hidden %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
    

    The advantage is that the special loop variable will count correctly; thus not counting the users not iterated over.

    If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence, you can render a default block by using else:

    <ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% else %}
        <li><em>no users found</em></li>
    {% endfor %}
    </ul>
    

    Note that, in Python, else blocks are executed whenever the corresponding loop did not break. Since Jinja loops cannot break anyway, a slightly different behavior of the else keyword was chosen.

    It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or RDFa. To use loops recursively, you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.

    The following example implements a sitemap with recursive loops:

    <ul class="sitemap">
    {%- for item in sitemap recursive %}
        <li><a href="{{ item.href|e }}">{{ item.title }}</a>
        {%- if item.children -%}
            <ul class="submenu">{{ loop(item.children) }}</ul>
        {%- endif %}</li>
    {%- endfor %}
    </ul>
    

    The loop variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind the variable loop by writing {% set outer_loop = loop %} after the loop that we want to use recursively. Then, we can call it using {{ outer_loop(…) }}

    Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope. Older versions of Jinja2 had a bug where in some circumstances it appeared that assignments would work. This is not supported. See Assignments for more information about how to deal with this.

    If all you want to do is check whether some value has changed since the last iteration or will change in the next iteration, you can use previtem and nextitem:

    {% for value in values %}
        {% if loop.previtem is defined and value > loop.previtem %}
            The value just increased!
        {% endif %}
        {{ value }}
        {% if loop.nextitem is defined and loop.nextitem > value %}
            The value will increase even more!
        {% endif %}
    {% endfor %}
    

    If you only care whether the value changed at all, using changed is even easier:

    {% for entry in entries %}
        {% if loop.changed(entry.category) %}
            <h2>{{ entry.category }}</h2>
        {% endif %}
        <p>{{ entry.message }}</p>
    {% endfor %}
    

    If¶

    The if statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:

    {% if users %}
    <ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
    </ul>
    {% endif %}
    

    For multiple branches, elif and else can be used like in Python. You can use more complex Expressions there, too:

    {% if kenny.sick %}
        Kenny is sick.
    {% elif kenny.dead %}
        You killed Kenny!  You bastard!!!
    {% else %}
        Kenny looks okay --- so far
    {% endif %}
    

    If can also be used as an inline expression and for loop filtering.

    Macros¶

    Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY�).

    Here’s a small example of a macro that renders a form element:

    {% macro input(name, value='', type='text', size=20) -%}
        <input type="{{ type }}" name="{{ name }}" value="{{
            value|e }}" size="{{ size }}">
    {%- endmacro %}
    

    The macro can then be called like a function in the namespace:

    <p>{{ input('username') }}</p>
    <p>{{ input('password', type='password') }}</p>
    

    If the macro was defined in a different template, you have to import it first.

    Inside macros, you have access to three special variables:

    varargs
    If more positional arguments are passed to the macro than accepted by the macro, they end up in the special varargs variable as a list of values.
    kwargs
    Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special variable.
    caller
    If the macro was called from a call tag, the caller is stored in this variable as a callable macro.

    Macros also expose some of their internal details. The following attributes are available on a macro object:

    name
    The name of the macro. {{ input.name }} will print input.
    arguments
    A tuple of the names of arguments the macro accepts.
    defaults
    A tuple of default values.
    catch_kwargs
    This is true if the macro accepts extra keyword arguments (i.e.: accesses the special kwargs variable).
    catch_varargs
    This is true if the macro accepts extra positional arguments (i.e.: accesses the special varargs variable).
    caller
    This is true if the macro accesses the special caller variable and may be called from a call tag.

    If a macro name starts with an underscore, it’s not exported and can’t be imported.

    Call¶

    In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special call block. The following example shows a macro that takes advantage of the call functionality and how it can be used:

    {% macro render_dialog(title, class='dialog') -%}
        <div class="{{ class }}">
            <h2>{{ title }}</h2>
            <div class="contents">
                {{ caller() }}
            </div>
        </div>
    {%- endmacro %}
    
    {% call render_dialog('Hello World') %}
        This is a simple dialog rendered by using a macro and
        a call block.
    {% endcall %}
    

    It’s also possible to pass arguments back to the call block. This makes it useful as a replacement for loops. Generally speaking, a call block works exactly like a macro without a name.

    Here’s an example of how a call block can be used with arguments:

    {% macro dump_users(users) -%}
        <ul>
        {%- for user in users %}
            <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
        {%- endfor %}
        </ul>
    {%- endmacro %}
    
    {% call(user) dump_users(list_of_user) %}
        <dl>
            <dl>Realname</dl>
            <dd>{{ user.realname|e }}</dd>
            <dl>Description</dl>
            <dd>{{ user.description }}</dd>
        </dl>
    {% endcall %}
    

    Filters¶

    Filter sections allow you to apply regular Jinja2 filters on a block of template data. Just wrap the code in the special filter section:

    {% filter upper %}
        This text becomes uppercase
    {% endfilter %}
    

    Assignments¶

    Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or loops) are exported from the template like top level macros and can be imported by other templates.

    Assignments use the set tag and can have multiple targets:

    {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
    {% set key, value = call_something() %}
    

    Scoping Behavior

    Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:

    {% set iterated = false %}
    {% for item in seq %}
        {{ item }}
        {% set iterated = true %}
    {% endfor %}
    {% if not iterated %} did not iterate {% endif %}
    

    It is not possible with Jinja syntax to do this. Instead use alternative constructs like the loop else block or the special loop variable:

    {% for item in seq %}
        {{ item }}
    {% else %}
        did not iterate
    {% endfor %}
    

    As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes:

    {% set ns = namespace(found=false) %}
    {% for item in items %}
        {% if item.check_something() %}
            {% set ns.found = true %}
        {% endif %}
        * {{ item.title }}
    {% endfor %}
    Found item having something: {{ ns.found }}
    

    Note hat the obj.attr notation in the set tag is only allowed for namespace objects; attempting to assign an attribute on any other object will raise an exception.

    New in version 2.10: Added support for namespace objects

    Block Assignments¶

    New in version 2.8.

    Starting with Jinja 2.8, it’s possible to also use block assignments to capture the contents of a block into a variable name. This can be useful in some situations as an alternative for macros. In that case, instead of using an equals sign and a value, you just write the variable name and then everything until {% endset %} is captured.

    Example:

    {% set navigation %}
        <li><a href="/">Index</a>
        <li><a href="/downloads">Downloads</a>
    {% endset %}
    

    The navigation variable then contains the navigation HTML source.

    Changed in version 2.10.

    Starting with Jinja 2.10, the block assignment supports filters.

    Example:

    {% set reply | wordwrap %}
        You wrote:
        {{ message }}
    {% endset %}
    

    Extends¶

    The extends tag can be used to extend one template from another. You can have multiple extends tags in a file, but only one of them may be executed at a time.

    See the section about Template Inheritance above.

    Blocks¶

    Blocks are used for inheritance and act as both placeholders and replacements at the same time. They are documented in detail in the Template Inheritance section.

    Include¶

    The include statement is useful to include a template and return the rendered contents of that file into the current namespace:

    {% include 'header.html' %}
        Body
    {% include 'footer.html' %}
    

    Included templates have access to the variables of the active context by default. For more details about context behavior of imports and includes, see Import Context Behavior.

    From Jinja 2.2 onwards, you can mark an include with ignore missing; in which case Jinja will ignore the statement if the template to be included does not exist. When combined with with or without context, it must be placed before the context visibility statement. Here are some valid examples:

    {% include "sidebar.html" ignore missing %}
    {% include "sidebar.html" ignore missing with context %}
    {% include "sidebar.html" ignore missing without context %}
    

    New in version 2.2.

    You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception.

    Example:

    {% include ['page_detailed.html', 'page.html'] %}
    {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
    

    Changed in version 2.4: If a template object was passed to the template context, you can include that object using include.

    Import¶

    Jinja2 supports putting often used code into macros. These macros can go into different templates and get imported from there. This works similarly to the import statements in Python. It’s important to know that imports are cached and imported templates don’t have access to the current template variables, just the globals by default. For more details about context behavior of imports and includes, see Import Context Behavior.

    There are two ways to import templates. You can import a complete template into a variable or request specific macros / exported variables from it.

    Imagine we have a helper module that renders forms (called forms.html):

    {% macro input(name, value='', type='text') -%}
        <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">
    {%- endmacro %}
    
    {%- macro textarea(name, value='', rows=10, cols=40) -%}
        <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols
            }}">{{ value|e }}</textarea>
    {%- endmacro %}
    

    The easiest and most flexible way to access a template’s variables and macros is to import the whole template module into a variable. That way, you can access the attributes:

    {% import 'forms.html' as forms %}
    <dl>
        <dt>Username</dt>
        <dd>{{ forms.input('username') }}</dd>
        <dt>Password</dt>
        <dd>{{ forms.input('password', type='password') }}</dd>
    </dl>
    <p>{{ forms.textarea('comment') }}</p>
    

    Alternatively, you can import specific names from a template into the current namespace:

    {% from 'forms.html' import input as input_field, textarea %}
    <dl>
        <dt>Username</dt>
        <dd>{{ input_field('username') }}</dd>
        <dt>Password</dt>
        <dd>{{ input_field('password', type='password') }}</dd>
    </dl>
    <p>{{ textarea('comment') }}</p>
    

    Macros and variables starting with one or more underscores are private and cannot be imported.

    Changed in version 2.4: If a template object was passed to the template context, you can import from that object.

    Import Context Behavior¶

    By default, included templates are passed the current context and imported templates are not. The reason for this is that imports, unlike includes, are cached; as imports are often used just as a module that holds macros.

    This behavior can be changed explicitly: by adding with context or without context to the import/include directive, the current context can be passed to the template and caching is disabled automatically.

    Here are two examples:

    {% from 'forms.html' import input with context %}
    {% include 'header.html' without context %}
    

    Note

    In Jinja 2.0, the context that was passed to the included template did not include variables defined in the template. As a matter of fact, this did not work:

    {% for box in boxes %}
        {% include "render_box.html" %}
    {% endfor %}
    

    The included template render_box.html is not able to access box in Jinja 2.0. As of Jinja 2.1, render_box.html is able to do so.

    Expressions¶

    Jinja allows basic expressions everywhere. These work very similarly to regular Python; even if you’re not working with Python you should feel comfortable with it.

    Literals¶

    The simplest form of expressions are literals. Literals are representations for Python objects such as strings and numbers. The following literals exist:

    “Hello World�:
    Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template).
    42 / 42.23:
    Integers and floating point numbers are created by just writing the number down. If a dot is present, the number is a float, otherwise an integer. Keep in mind that, in Python, 42 and 42.0 are different (int and float, respectively).
    [‘list’, ‘of’, ‘objects’]:

    Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop:

    <ul>
    {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
                             ('downloads.html', 'Downloads')] %}
        <li><a href="{{ href }}">{{ caption }}</a></li>
    {% endfor %}
    </ul>
    
    (‘tuple’, ‘of’, ‘values’):
    Tuples are like lists that cannot be modified (“immutable�). If a tuple only has one item, it must be followed by a comma (('1-tuple',)). Tuples are usually used to represent items of two or more elements. See the list example above for more details.
    {‘dict’: ‘of’, ‘key’: ‘and’, ‘value’: ‘pairs’}:
    A dict in Python is a structure that combines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in templates; they are useful in some rare cases such as the xmlattr() filter.
    true / false:
    true is always true and false is always false.

    Note

    The special constants true, false, and none are indeed lowercase. Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false), all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase) you should use the lowercase versions.

    Math¶

    Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness’ sake. The following operators are supported:

    +
    Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the ~ operator. {{ 1 + 1 }} is 2.
    -
    Subtract the second number from the first one. {{ 3 - 2 }} is 1.
    /
    Divide two numbers. The return value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}. (Just like from __future__ import division.)
    //
    Divide two numbers and return the truncated integer result. {{ 20 // 7 }} is 2.
    %
    Calculate the remainder of an integer division. {{ 11 % 7 }} is 4.
    *
    Multiply the left operand with the right one. {{ 2 * 2 }} would return 4. This can also be used to repeat a string multiple times. {{ '=' * 80 }} would print a bar of 80 equal signs.
    **
    Raise the left operand to the power of the right operand. {{ 2**3 }} would return 8.

    Comparisons¶

    ==
    Compares two objects for equality.
    !=
    Compares two objects for inequality.
    >
    true if the left hand side is greater than the right hand side.
    >=
    true if the left hand side is greater or equal to the right hand side.
    <
    true if the left hand side is lower than the right hand side.
    <=
    true if the left hand side is lower or equal to the right hand side.

    Logic¶

    For if statements, for filtering, and if expressions, it can be useful to combine multiple expressions:

    and
    Return true if the left and the right operand are true.
    or
    Return true if the left or the right operand are true.
    not
    negate a statement (see below).
    (expr)
    group an expression.

    Note

    The is and in operators support negation using an infix notation, too: foo is not bar and foo not in bar instead of not foo is bar and not foo in bar. All other expressions require a prefix notation: not (foo and bar).

    Other Operators¶

    The following operators are very useful but don’t fit into any of the other two categories:

    in
    Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. {{ 1 in [1, 2, 3] }} would, for example, return true.
    is
    Performs a test.
    |
    Applies a filter.
    ~

    Converts all operands into strings and concatenates them.

    {{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John') Hello John!.

    ()

    Call a callable: {{ post.render() }}. Inside of the parentheses you can use positional arguments and keyword arguments like in Python:

    {{ post.render(user, full=true) }}.

    . / []
    Get an attribute of an object. (See Variables)

    If Expression¶

    It is also possible to use inline if expressions. These are useful in some situations. For example, you can use this to extend from one template if a variable is defined, otherwise from the default layout template:

    {% extends layout_template if layout_template is defined else 'master.html' %}
    

    The general syntax is <do something> if <something is true> else <do something else>.

    The else part is optional. If not provided, the else block implicitly evaluates into an undefined object:

    .. sourcecode:: jinja
    
    {{ ‘[%s]’ % page.title if page.title }}

    List of Builtin Filters¶

    abs()¶

    Return the absolute value of the argument.

    attr(obj, name)¶

    Get an attribute of an object. foo|attr("bar") works like foo.bar, but returns undefined instead of falling back to foo["bar"] if the attribute doesn’t exist.

    See Notes on subscriptions for more details.

    batch(value, linecount, fill_with=None)¶

    A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:

    <table>
    {%- for row in items|batch(3, '&nbsp;') %}
      <tr>
      {%- for column in row %}
        <td>{{ column }}</td>
      {%- endfor %}
      </tr>
    {%- endfor %}
    </table>
    
    capitalize(s)¶

    Capitalize a value. The first character will be uppercase, all others lowercase.

    center(value, width=80)¶

    Centers the value in a field of a given width.

    default(value, default_value='', boolean=False)¶

    If the value is undefined it will return the passed default value, otherwise the value of the variable:

    {{ my_variable|default('my_variable is not defined') }}
    

    This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not defined'. If you want to use default with variables that evaluate to false you have to set the second parameter to true:

    {{ ''|default('the string was empty', true) }}
    
    Aliases:d
    dictsort(value, case_sensitive=False, by='key', reverse=False)¶

    Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:

    {% for item in mydict|dictsort %}
        sort the dict by key, case insensitive
    
    {% for item in mydict|dictsort(reverse=true) %}
        sort the dict by key, case insensitive, reverse order
    
    {% for item in mydict|dictsort(true) %}
        sort the dict by key, case sensitive
    
    {% for item in mydict|dictsort(false, 'value') %}
        sort the dict by value, case insensitive
    
    escape(s)¶

    Convert the characters &, <, >, ‘, and � in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

    Aliases:e
    filesizeformat(value, binary=False)¶

    Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi).

    first()¶

    Return the first item of a sequence.

    float(value, default=0.0)¶

    Convert the value into a floating point number. If the conversion doesn’t work it will return 0.0. You can override this default using the first parameter.

    forceescape(value)¶

    Enforce HTML escaping. This will probably double escape variables.

    format(value, *args, **kwargs)¶

    Apply python string formatting on an object:

    {{ "%s - %s"|format("Hello?", "Foo!") }}
        -> Hello? - Foo!
    
    groupby()¶

    Group a sequence of objects by a common attribute.

    If you for example have a list of dicts or objects that represent persons with gender, first_name and last_name attributes and you want to group all users by genders you can do something like the following snippet:

    <ul>
    {% for group in persons|groupby('gender') %}
        <li>{{ group.grouper }}<ul>
        {% for person in group.list %}
            <li>{{ person.first_name }} {{ person.last_name }}</li>
        {% endfor %}</ul></li>
    {% endfor %}
    </ul>
    

    Additionally it’s possible to use tuple unpacking for the grouper and list:

    <ul>
    {% for grouper, list in persons|groupby('gender') %}
        ...
    {% endfor %}
    </ul>
    

    As you can see the item we’re grouping by is stored in the grouper attribute and the list contains all the objects that have this grouper in common.

    Changed in version 2.6: It’s now possible to use dotted notation to group by the child attribute of another attribute.

    indent(s, width=4, first=False, blank=False, indentfirst=None)¶

    Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.

    Parameters:
    • width – Number of spaces to indent by.
    • first – Don’t skip indenting the first line.
    • blank – Don’t skip indenting empty lines.

    Changed in version 2.10: Blank lines are not indented by default.

    Rename the indentfirst argument to first.

    int(value, default=0, base=10)¶

    Convert the value into an integer. If the conversion doesn’t work it will return 0. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values.

    join()¶

    Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:

    {{ [1, 2, 3]|join('|') }}
        -> 1|2|3
    
    {{ [1, 2, 3]|join }}
        -> 123
    

    It is also possible to join certain attributes of an object:

    {{ users|join(', ', attribute='username') }}
    

    New in version 2.6: The attribute parameter was added.

    last(seq)¶

    Return the last item of a sequence.

    length()¶

    Return the number of items in a container.

    Aliases:count
    list()¶

    Convert the value into a list. If it was a string the returned list will be a list of characters.

    lower(s)¶

    Convert a value to lowercase.

    map()¶

    Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.

    The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:

    Users on this page: {{ users|map(attribute='username')|join(', ') }}
    

    Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:

    Users on this page: {{ titles|map('lower')|join(', ') }}
    

    New in version 2.7.

    max(value, case_sensitive=False, attribute=None)¶

    Return the largest item from the sequence.

    {{ [1, 2, 3]|max }}
        -> 3
    
    Parameters:
    • case_sensitive – Treat upper and lower case strings as distinct.
    • attribute – Get the object with the max value of this attribute.
    min(value, case_sensitive=False, attribute=None)¶

    Return the smallest item from the sequence.

    {{ [1, 2, 3]|min }}
        -> 1
    
    Parameters:
    • case_sensitive – Treat upper and lower case strings as distinct.
    • attribute – Get the object with the max value of this attribute.
    pprint(value, verbose=False)¶

    Pretty print a variable. Useful for debugging.

    With Jinja 1.2 onwards you can pass it a parameter. If this parameter is truthy the output will be more verbose (this requires pretty)

    random(seq)¶

    Return a random item from the sequence.

    reject()¶

    Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.

    If no test is specified, each object will be evaluated as a boolean.

    Example usage:

    {{ numbers|reject("odd") }}
    

    New in version 2.7.

    rejectattr()¶

    Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.

    If no test is specified, the attribute’s value will be evaluated as a boolean.

    {{ users|rejectattr("is_active") }}
    {{ users|rejectattr("email", "none") }}
    

    New in version 2.7.

    replace(s, old, new, count=None)¶

    Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument count is given, only the first count occurrences are replaced:

    {{ "Hello World"|replace("Hello", "Goodbye") }}
        -> Goodbye World
    
    {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
        -> d'oh, d'oh, aaargh
    
    reverse(value)¶

    Reverse the object or return an iterator that iterates over it the other way round.

    round(value, precision=0, method='common')¶

    Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:

    • 'common' rounds either up or down
    • 'ceil' always rounds up
    • 'floor' always rounds down

    If you don’t specify a method 'common' is used.

    {{ 42.55|round }}
        -> 43.0
    {{ 42.55|round(1, 'floor') }}
        -> 42.5
    

    Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:

    {{ 42.55|round|int }}
        -> 43
    
    safe(value)¶

    Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.

    select()¶

    Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.

    If no test is specified, each object will be evaluated as a boolean.

    Example usage:

    {{ numbers|select("odd") }}
    {{ numbers|select("odd") }}
    {{ numbers|select("divisibleby", 3) }}
    {{ numbers|select("lessthan", 42) }}
    {{ strings|select("equalto", "mystring") }}
    

    New in version 2.7.

    selectattr()¶

    Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.

    If no test is specified, the attribute’s value will be evaluated as a boolean.

    Example usage:

    {{ users|selectattr("is_active") }}
    {{ users|selectattr("email", "none") }}
    

    New in version 2.7.

    slice()¶

    Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:

    <div class="columwrapper">
      {%- for column in items|slice(3) %}
        <ul class="column-{{ loop.index }}">
        {%- for item in column %}
          <li>{{ item }}</li>
        {%- endfor %}
        </ul>
      {%- endfor %}
    </div>
    

    If you pass it a second argument it’s used to fill missing values on the last iteration.

    sort(value, reverse=False, case_sensitive=False, attribute=None)¶

    Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting.

    If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default.

    {% for item in iterable|sort %}
        ...
    {% endfor %}
    

    It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the attribute parameter:

    {% for item in iterable|sort(attribute='date') %}
        ...
    {% endfor %}
    

    Changed in version 2.6: The attribute parameter was added.

    string(object)¶

    Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.

    striptags(value)¶

    Strip SGML/XML tags and replace adjacent whitespace by one space.

    sum()¶

    Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.

    It is also possible to sum up only certain attributes:

    Total: {{ items|sum(attribute='price') }}
    

    Changed in version 2.6: The attribute parameter was added to allow suming up over attributes. Also the start parameter was moved on to the right.

    title(s)¶

    Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.

    tojson(value, indent=None)¶

    Dumps a structure to JSON so that it’s safe to use in <script> tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the |tojson filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of <script> tags.

    The following characters are escaped in strings:

    • <
    • >
    • &
    • '

    This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition.

    The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with.

    Note that this filter is for use in HTML contexts only.

    New in version 2.9.

    trim(value)¶

    Strip leading and trailing whitespace.

    truncate(s, length=255, killwords=False, end='...', leeway=None)¶

    Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.

    {{ "foo bar baz qux"|truncate(9) }}
        -> "foo..."
    {{ "foo bar baz qux"|truncate(9, True) }}
        -> "foo ba..."
    {{ "foo bar baz qux"|truncate(11) }}
        -> "foo bar baz qux"
    {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
        -> "foo bar..."
    

    The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally.

    unique(value, case_sensitive=False, attribute=None)¶

    Returns a list of unique items from the the given iterable.

    {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
        -> ['foo', 'bar', 'foobar']
    

    The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.

    Parameters:
    • case_sensitive – Treat upper and lower case strings as distinct.
    • attribute – Filter objects with unique values for this attribute.
    upper(s)¶

    Convert a value to uppercase.

    urlencode(value)¶

    Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.

    New in version 2.7.

    urlize(value, trim_url_limit=None, nofollow=False, target=None, rel=None)¶

    Converts URLs in plain text into clickable links.

    If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls “nofollow�:

    {{ mytext|urlize(40, true) }}
        links are shortened to 40 chars and defined with rel="nofollow"
    

    If target is specified, the target attribute will be added to the <a> tag:

    {{ mytext|urlize(40, target='_blank') }}
    

    Changed in version 2.8+: The target parameter was added.

    wordcount(s)¶

    Count the words in that string.

    wordwrap(s, width=79, break_long_words=True, wrapstring=None)¶

    Return a copy of the string passed to the filter wrapped after 79 characters. You can override this default using the first parameter. If you set the second parameter to false Jinja will not split words apart if they are longer than width. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument.

    New in version 2.7: Added support for the wrapstring parameter.

    xmlattr(d, autospace=True)¶

    Create an SGML/XML attribute string based on the items in a dict.

    Values that are neither none nor undefined are automatically escaped, safely allowing untrusted user input.

    User input should not be used as keys to this filter. If any key contains a space, / solidus, > greater-than sign, or = equals sign, this fails with a ValueError. Regardless of this, user input should never be used as keys to this filter, or must be separately validated first.

    <ul{{ {'class': 'my_list', 'missing': none,
            'id': 'list-%d'|format(variable)}|xmlattr }}>
    ...
    </ul>
    

    Results in something like this:

    <ul class="my_list" id="list-42">
    ...
    </ul>
    

    As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false.

    List of Builtin Tests¶

    callable()¶

    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a __call__() method.

    defined(value)¶

    Return true if the variable is defined:

    {% if variable is defined %}
        value of variable: {{ variable }}
    {% else %}
        variable is not defined
    {% endif %}
    

    See the default() filter for a simple way to set undefined variables.

    divisibleby(value, num)¶

    Check if a variable is divisible by a number.

    eq(a, b)¶
    Aliases:==, equalto
    escaped(value)¶

    Check if the value is escaped.

    even(value)¶

    Return true if the variable is even.

    ge(a, b)¶
    Aliases:>=
    gt(a, b)¶
    Aliases:>, greaterthan
    in(value, seq)¶

    Check if value is in seq.

    New in version 2.10.

    iterable(value)¶

    Check if it’s possible to iterate over an object.

    le(a, b)¶
    Aliases:<=
    lower(value)

    Return true if the variable is lowercased.

    lt(a, b)¶
    Aliases:<, lessthan
    mapping(value)¶

    Return true if the object is a mapping (dict etc.).

    New in version 2.6.

    ne(a, b)¶
    Aliases:!=
    none(value)¶

    Return true if the variable is none.

    number(value)¶

    Return true if the variable is a number.

    odd(value)¶

    Return true if the variable is odd.

    sameas(value, other)¶

    Check if an object points to the same memory address than another object:

    {% if foo.attribute is sameas false %}
        the foo attribute really is the `False` singleton
    {% endif %}
    
    sequence(value)¶

    Return true if the variable is a sequence. Sequences are variables that are iterable.

    string(value)

    Return true if the object is a string.

    undefined(value)¶

    Like defined() but the other way round.

    upper(value)

    Return true if the variable is uppercased.

    List of Global Functions¶

    The following functions are available in the global scope by default:

    range([start, ]stop[, step])¶

    Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) and range(0, 4, 1) return [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.

    This is useful to repeat a template block multiple times, e.g. to fill a list. Imagine you have 7 users in the list but you want to render three empty items to enforce a height with CSS:

    <ul>
    {% for user in users %}
        <li>{{ user.username }}</li>
    {% endfor %}
    {% for number in range(10 - users|count) %}
        <li class="empty"><span>...</span></li>
    {% endfor %}
    </ul>
    
    lipsum(n=5, html=True, min=20, max=100)¶

    Generates some lorem ipsum for the template. By default, five paragraphs of HTML are generated with each paragraph between 20 and 100 words. If html is False, regular text is returned. This is useful to generate simple contents for layout testing.

    dict(**items)¶

    A convenient alternative to dict literals. {'foo': 'bar'} is the same as dict(foo='bar').

    class cycler(*items)¶

    The cycler allows you to cycle among values similar to how loop.cycle works. Unlike loop.cycle, you can use this cycler outside of loops or over multiple loops.

    This can be very useful if you want to show a list of folders and files with the folders on top but both in the same list with alternating row colors.

    The following example shows how cycler can be used:

    {% set row_class = cycler('odd', 'even') %}
    <ul class="browser">
    {% for folder in folders %}
      <li class="folder {{ row_class.next() }}">{{ folder|e }}</li>
    {% endfor %}
    {% for filename in files %}
      <li class="file {{ row_class.next() }}">{{ filename|e }}</li>
    {% endfor %}
    </ul>
    

    A cycler has the following attributes and methods:

    reset()¶

    Resets the cycle to the first item.

    next()¶

    Goes one item ahead and returns the then-current item.

    current¶

    Returns the current item.

    New in version 2.1.

    class joiner(sep=', ')¶

    A tiny helper that can be used to “join� multiple sections. A joiner is passed a string and will return that string every time it’s called, except the first time (in which case it returns an empty string). You can use this to join things:

    {% set pipe = joiner("|") %}
    {% if categories %} {{ pipe() }}
        Categories: {{ categories|join(", ") }}
    {% endif %}
    {% if author %} {{ pipe() }}
        Author: {{ author() }}
    {% endif %}
    {% if can_edit %} {{ pipe() }}
        <a href="?action=edit">Edit</a>
    {% endif %}
    

    New in version 2.1.

    class namespace(...)¶

    Creates a new container that allows attribute assignment using the {% set %} tag:

    {% set ns = namespace() %}
    {% set ns.foo = 'bar' %}
    

    The main purpose of this is to allow carrying a value from within a loop body to an outer scope. Initial values can be provided as a dict, as keyword arguments, or both (same behavior as Python’s dict constructor):

    {% set ns = namespace(found=false) %}
    {% for item in items %}
        {% if item.check_something() %}
            {% set ns.found = true %}
        {% endif %}
        * {{ item.title }}
    {% endfor %}
    Found item having something: {{ ns.found }}
    

    New in version 2.10.

    Extensions¶

    The following sections cover the built-in Jinja2 extensions that may be enabled by an application. An application could also provide further extensions not covered by this documentation; in which case there should be a separate document explaining said extensions.

    i18n¶

    If the i18n extension is enabled, it’s possible to mark parts in the template as translatable. To mark a section as translatable, you can use trans:

    <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
    

    To translate a template expression — say, using template filters, or by just accessing an attribute of an object — you need to bind the expression to a name for use within the translation block:

    <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>
    

    If you need to bind more than one expression inside a trans tag, separate the pieces with a comma (,):

    {% trans book_title=book.title, author=author.name %}
    This is {{ book_title }} by {{ author }}
    {% endtrans %}
    

    Inside trans tags no statements are allowed, only variable tags are.

    To pluralize, specify both the singular and plural forms with the pluralize tag, which appears between trans and endtrans:

    {% trans count=list|length %}
    There is {{ count }} {{ name }} object.
    {% pluralize %}
    There are {{ count }} {{ name }} objects.
    {% endtrans %}
    

    By default, the first variable in a block is used to determine the correct singular or plural form. If that doesn’t work out, you can specify the name which should be used for pluralizing by adding it as parameter to pluralize:

    {% trans ..., user_count=users|length %}...
    {% pluralize user_count %}...{% endtrans %}
    

    When translating longer blocks of text, whitespace and linebreaks result in rather ugly and error-prone translation strings. To avoid this, a trans block can be marked as trimmed which will replace all linebreaks and the whitespace surrounding them with a single space and remove leading/trailing whitespace:

    {% trans trimmed book_title=book.title %}
        This is {{ book_title }}.
        You should read it!
    {% endtrans %}
    

    If trimming is enabled globally, the notrimmed modifier can be used to disable it for a trans block.

    New in version 2.10: The trimmed and notrimmed modifiers have been added.

    It’s also possible to translate strings in expressions. For that purpose, three functions exist:

    • gettext: translate a single string
    • ngettext: translate a pluralizable string
    • _: alias for gettext

    For example, you can easily print a translated string like this:

    {{ _('Hello World!') }}
    

    To use placeholders, use the format filter:

    {{ _('Hello %(user)s!')|format(user=user.username) }}
    

    For multiple placeholders, always use keyword arguments to format, as other languages may not use the words in the same order.

    Changed in version 2.5.

    If newstyle gettext calls are activated (Whitespace Trimming), using placeholders is a lot easier:

    {{ gettext('Hello World!') }}
    {{ gettext('Hello %(name)s!', name='World') }}
    {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
    

    Note that the ngettext function’s format string automatically receives the count as a num parameter in addition to the regular parameters.

    Expression Statement¶

    If the expression-statement extension is loaded, a tag called do is available that works exactly like the regular variable expression ({{ ... }}); except it doesn’t print anything. This can be used to modify lists:

    {% do navigation.append('a string') %}
    

    Loop Controls¶

    If the application enables the Loop Controls, it’s possible to use break and continue in loops. When break is reached, the loop is terminated; if continue is reached, the processing is stopped and continues with the next iteration.

    Here’s a loop that skips every second item:

    {% for user in users %}
        {%- if loop.index is even %}{% continue %}{% endif %}
        ...
    {% endfor %}
    

    Likewise, a loop that stops processing after the 10th iteration:

    {% for user in users %}
        {%- if loop.index >= 10 %}{% break %}{% endif %}
    {%- endfor %}
    

    Note that loop.index starts with 1, and loop.index0 starts with 0 (See: For).

    With Statement¶

    New in version 2.3.

    The with statement makes it possible to create a new inner scope. Variables set within this scope are not visible outside of the scope.

    With in a nutshell:

    {% with %}
        {% set foo = 42 %}
        {{ foo }}           foo is 42 here
    {% endwith %}
    foo is not visible here any longer
    

    Because it is common to set variables at the beginning of the scope, you can do that within the with statement. The following two examples are equivalent:

    {% with foo = 42 %}
        {{ foo }}
    {% endwith %}
    
    {% with %}
        {% set foo = 42 %}
        {{ foo }}
    {% endwith %}
    

    An important note on scoping here. In Jinja versions before 2.9 the behavior of referencing one variable to another had some unintended consequences. In particular one variable could refer to another defined in the same with block’s opening statement. This caused issues with the cleaned up scoping behavior and has since been improved. In particular in newer Jinja2 versions the following code always refers to the variable a from outside the with block:

    {% with a={}, b=a.attribute %}...{% endwith %}
    

    In earlier Jinja versions the b attribute would refer to the results of the first attribute. If you depend on this behavior you can rewrite it to use the set tag:

    {% with a={} %}
        {% set b = a.attribute %}
    {% endwith %}
    

    Extension

    In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It’s now enabled by default.

    Autoescape Overrides¶

    New in version 2.4.

    If you want you can activate and deactivate the autoescaping from within the templates.

    Example:

    {% autoescape true %}
        Autoescaping is active within this block
    {% endautoescape %}
    
    {% autoescape false %}
        Autoescaping is inactive within this block
    {% endautoescape %}
    

    After an endautoescape the behavior is reverted to what it was before.

    Extension

    In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It’s now enabled by default.

    PKê|>]hm-7::html/tricks.htmlnu„[µü¤ Tips and Tricks — Jinja2 2.10.1 documentation

    Tips and Tricks¶

    This part of the documentation shows some tips and tricks for Jinja2 templates.

    Null-Master Fallback¶

    Jinja2 supports dynamic inheritance and does not distinguish between parent and child template as long as no extends tag is visited. While this leads to the surprising behavior that everything before the first extends tag including whitespace is printed out instead of being ignored, it can be used for a neat trick.

    Usually child templates extend from one template that adds a basic HTML skeleton. However it’s possible to put the extends tag into an if tag to only extend from the layout template if the standalone variable evaluates to false which it does per default if it’s not defined. Additionally a very basic skeleton is added to the file so that if it’s indeed rendered with standalone set to True a very basic HTML skeleton is added:

    {% if not standalone %}{% extends 'master.html' %}{% endif -%}
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <title>{% block title %}The Page Title{% endblock %}</title>
    <link rel="stylesheet" href="style.css" type="text/css">
    {% block body %}
      <p>This is the page body.</p>
    {% endblock %}
    

    Alternating Rows¶

    If you want to have different styles for each row of a table or list you can use the cycle method on the loop object:

    <ul>
    {% for row in rows %}
      <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
    {% endfor %}
    </ul>
    

    cycle can take an unlimited amount of strings. Each time this tag is encountered the next item from the list is rendered.

    Highlighting Active Menu Items¶

    Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s possible to define the active menu item in the child template:

    {% extends "layout.html" %}
    {% set active_page = "index" %}
    

    The layout template can then access active_page. Additionally it makes sense to define a default for that variable:

    {% set navigation_bar = [
        ('/', 'index', 'Index'),
        ('/downloads/', 'downloads', 'Downloads'),
        ('/about/', 'about', 'About')
    ] -%}
    {% set active_page = active_page|default('index') -%}
    ...
    <ul id="navigation">
    {% for href, id, caption in navigation_bar %}
      <li{% if id == active_page %} class="active"{% endif
      %}><a href="{{ href|e }}">{{ caption|e }}</a></li>
    {% endfor %}
    </ul>
    ...
    

    Accessing the parent Loop¶

    The special loop variable always points to the innermost loop. If it’s desired to have access to an outer loop it’s possible to alias it:

    <table>
    {% for row in table %}
      <tr>
      {% set rowloop = loop %}
      {% for cell in row %}
        <td id="cell-{{ rowloop.index }}-{{ loop.index }}">{{ cell }}</td>
      {% endfor %}
      </tr>
    {% endfor %}
    </table>
    
    PKê|>]î£ç[OOAUTHORSnu„[µü¤Jinja is written and maintained by the Jinja Team and various contributors: Lead Developer: - Armin Ronacher Developers: - Christoph Hack - Georg Brandl Contributors: - Bryan McLemore - Mickaël Guérin - Cameron Knight - Lawrence Journal-World. - David Cramer - Adrian Mönnich (ThiefMaster) Patches and suggestions: - Ronny Pfannschmidt - Axel Böhm - Alexey Melchakov - Bryan McLemore - Clovis Fabricio (nosklo) - Cameron Knight - Peter van Dijk (Habbie) - Stefan Ebner - Rene Leonhardt - Thomas Waldmann - Cory Benfield (Lukasa) PKê|>]ÚÆ9ã^ã^ CHANGES.rstnu„[µü¤Jinja Changelog =============== Version 2.10.1 -------------- Released 2019-04-06 - ``SandboxedEnvironment`` securely handles ``str.format_map`` in order to prevent code execution through untrusted format strings. The sandbox already handled ``str.format``. Version 2.10 ------------ released on November 8th 2017 - Added a new extension node called ``OverlayScope`` which can be used to create an unoptimized scope that will look up all variables from a derived context. - Added an ``in`` test that works like the in operator. This can be used in combination with ``reject`` and ``select``. - Added ``previtem`` and ``nextitem`` to loop contexts, providing access to the previous/next item in the loop. If such an item does not exist, the value is undefined. - Added ``changed(*values)`` to loop contexts, providing an easy way of checking whether a value has changed since the last iteration (or rather since the last call of the method) - Added a ``namespace`` function that creates a special object which allows attribute assignment using the ``set`` tag. This can be used to carry data across scopes, e.g. from a loop body to code that comes after the loop. - Added a ``trimmed`` modifier to ``{% trans %}`` to strip linebreaks and surrounding whitespace. Also added a new policy to enable this for all ``trans`` blocks. - The ``random`` filter is no longer incorrectly constant folded and will produce a new random choice each time the template is rendered. (`#478`_) - Added a ``unique`` filter. (`#469`_) - Added ``min`` and ``max`` filters. (`#475`_) - Added tests for all comparison operators: ``eq``, ``ne``, ``lt``, ``le``, ``gt``, ``ge``. (`#665`_) - ``import`` statement cannot end with a trailing comma. (`#617`_, `#618`_) - ``indent`` filter will not indent blank lines by default. (`#685`_) - Add ``reverse`` argument for ``dictsort`` filter. (`#692`_) - Add a ``NativeEnvironment`` that renders templates to native Python types instead of strings. (`#708`_) - Added filter support to the block ``set`` tag. (`#489`_) - ``tojson`` filter marks output as safe to match documented behavior. (`#718`_) - Resolved a bug where getting debug locals for tracebacks could modify template context. - Fixed a bug where having many ``{% elif ... %}`` blocks resulted in a "too many levels of indentation" error. These blocks now compile to native ``elif ..:`` instead of ``else: if ..:`` (`#759`_) .. _#469: https://github.com/pallets/jinja/pull/469 .. _#475: https://github.com/pallets/jinja/pull/475 .. _#478: https://github.com/pallets/jinja/pull/478 .. _#489: https://github.com/pallets/jinja/pull/489 .. _#617: https://github.com/pallets/jinja/pull/617 .. _#618: https://github.com/pallets/jinja/pull/618 .. _#665: https://github.com/pallets/jinja/pull/665 .. _#685: https://github.com/pallets/jinja/pull/685 .. _#692: https://github.com/pallets/jinja/pull/692 .. _#708: https://github.com/pallets/jinja/pull/708 .. _#718: https://github.com/pallets/jinja/pull/718 .. _#759: https://github.com/pallets/jinja/pull/759 Version 2.9.6 ------------- (bugfix release, released on April 3rd 2017) - Fixed custom context behavior in fast resolve mode (#675) Version 2.9.5 ------------- (bugfix release, released on January 28th 2017) - Restored the original repr of the internal ``_GroupTuple`` because this caused issues with ansible and it was an unintended change. (#654) - Added back support for custom contexts that override the old ``resolve`` method since it was hard for people to spot that this could cause a regression. - Correctly use the buffer for the else block of for loops. This caused invalid syntax errors to be caused on 2.x and completely wrong behavior on Python 3 (#669) - Resolve an issue where the ``{% extends %}`` tag could not be used with async environments. (#668) - Reduce memory footprint slightly by reducing our unicode database dump we use for identifier matching on Python 3 (#666) - Fixed autoescaping not working for macros in async compilation mode. (#671) Version 2.9.4 ------------- (bugfix release, released on January 10th 2017) - Solved some warnings for string literals. (#646) - Increment the bytecode cache version which was not done due to an oversight before. - Corrected bad code generation and scoping for filtered loops. (#649) - Resolved an issue where top-level output silencing after known extend blocks could generate invalid code when blocks where contained in if statements. (#651) - Made the ``truncate.leeway`` default configurable to improve compatibility with older templates. Version 2.9.3 ------------- (bugfix release, released on January 8th 2017) - Restored the use of blocks in macros to the extend that was possible before. On Python 3 it would render a generator repr instead of the block contents. (#645) - Set a consistent behavior for assigning of variables in inner scopes when the variable is also read from an outer scope. This now sets the intended behavior in all situations however it does not restore the old behavior where limited assignments to outer scopes was possible. For more information and a discussion see #641 - Resolved an issue where ``block scoped`` would not take advantage of the new scoping rules. In some more exotic cases a variable overriden in a local scope would not make it into a block. - Change the code generation of the ``with`` statement to be in line with the new scoping rules. This resolves some unlikely bugs in edge cases. This also introduces a new internal ``With`` node that can be used by extensions. Version 2.9.2 ------------- (bugfix release, released on January 8th 2017) - Fixed a regression that caused for loops to not be able to use the same variable for the target as well as source iterator. (#640) - Add support for a previously unknown behavior of macros. It used to be possible in some circumstances to explicitly provide a caller argument to macros. While badly buggy and unintended it turns out that this is a common case that gets copy pasted around. To not completely break backwards compatibility with the most common cases it's now possible to provide an explicit keyword argument for caller if it's given an explicit default. (#642) Version 2.9.1 ------------- (bugfix release, released on January 7th 2017) - Resolved a regression with call block scoping for macros. Nested caller blocks that used the same identifiers as outer macros could refer to the wrong variable incorrectly. Version 2.9 ----------- (codename Derivation, released on January 7th 2017) - Change cache key definition in environment. This fixes a performance regression introduced in 2.8. - Added support for ``generator_stop`` on supported Python versions (Python 3.5 and later) - Corrected a long standing issue with operator precedence of math operations not being what was expected. - Added support for Python 3.6 async iterators through a new async mode. - Added policies for filter defaults and similar things. - urlize now sets "rel noopener" by default. - Support attribute fallback for old-style classes in 2.x. - Support toplevel set statements in extend situations. - Restored behavior of Cycler for Python 3 users. - Subtraction now follows the same behavior as other operators on undefined values. - ``map`` and friends will now give better error messages if you forgot to quote the parameter. - Depend on MarkupSafe 0.23 or higher. - Improved the ``truncate`` filter to support better truncation in case the string is barely truncated at all. - Change the logic for macro autoescaping to be based on the runtime autoescaping information at call time instead of macro define time. - Ported a modified version of the ``tojson`` filter from Flask to Jinja2 and hooked it up with the new policy framework. - Block sets are now marked ``safe`` by default. - On Python 2 the asciification of ASCII strings can now be disabled with the ``compiler.ascii_str`` policy. - Tests now no longer accept an arbitrary expression as first argument but a restricted one. This means that you can now properly use multiple tests in one expression without extra parentheses. In particular you can now write ``foo is divisibleby 2 or foo is divisibleby 3`` as you would expect. - Greatly changed the scoping system to be more consistent with what template designers and developers expect. There is now no more magic difference between the different include and import constructs. Context is now always propagated the same way. The only remaining differences is the defaults for ``with context`` and ``without context``. - The ``with`` and ``autoescape`` tags are now built-in. - Added the new ``select_autoescape`` function which helps configuring better autoescaping easier. - Fixed a runtime error in the sandbox when attributes of async generators were accessed. Version 2.8.1 ------------- (bugfix release, released on December 29th 2016) - Fixed the ``for_qs`` flag for ``urlencode``. - Fixed regression when applying ``int`` to non-string values. - SECURITY: if the sandbox mode is used format expressions are now sandboxed with the same rules as in Jinja. This solves various information leakage problems that can occur with format strings. Version 2.8 ----------- (codename Replacement, released on July 26th 2015) - Added ``target`` parameter to urlize function. - Added support for ``followsymlinks`` to the file system loader. - The truncate filter now counts the length. - Added equalto filter that helps with select filters. - Changed cache keys to use absolute file names if available instead of load names. - Fixed loop length calculation for some iterators. - Changed how Jinja2 enforces strings to be native strings in Python 2 to work when people break their default encoding. - Added :func:`make_logging_undefined` which returns an undefined object that logs failures into a logger. - If unmarshalling of cached data fails the template will be reloaded now. - Implemented a block ``set`` tag. - Default cache size was increased to 400 from a low 50. - Fixed ``is number`` test to accept long integers in all Python versions. - Changed ``is number`` to accept Decimal as a number. - Added a check for default arguments followed by non-default arguments. This change makes ``{% macro m(x, y=1, z) %}...{% endmacro %}`` a syntax error. The previous behavior for this code was broken anyway (resulting in the default value being applied to ``y``). - Add ability to use custom subclasses of ``jinja2.compiler.CodeGenerator`` and ``jinja2.runtime.Context`` by adding two new attributes to the environment (``code_generator_class`` and ``context_class``) (pull request ``#404``). - added support for context/environment/evalctx decorator functions on the finalize callback of the environment. - escape query strings for urlencode properly. Previously slashes were not escaped in that place. - Add 'base' parameter to 'int' filter. Version 2.7.3 ------------- (bugfix release, released on June 6th 2014) - Security issue: Corrected the security fix for the cache folder. This fix was provided by RedHat. Version 2.7.2 ------------- (bugfix release, released on January 10th 2014) - Prefix loader was not forwarding the locals properly to inner loaders. This is now fixed. - Security issue: Changed the default folder for the filesystem cache to be user specific and read and write protected on UNIX systems. See `Debian bug 734747`_ for more information. .. _Debian bug 734747: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734747 Version 2.7.1 ------------- (bugfix release, released on August 7th 2013) - Fixed a bug with ``call_filter`` not working properly on environment and context filters. - Fixed lack of Python 3 support for bytecode caches. - Reverted support for defining blocks in included templates as this broke existing templates for users. - Fixed some warnings with hashing of undefineds and nodes if Python is run with warnings for Python 3. - Added support for properly hashing undefined objects. - Fixed a bug with the title filter not working on already uppercase strings. Version 2.7 ----------- (codename Translation, released on May 20th 2013) - Choice and prefix loaders now dispatch source and template lookup separately in order to work in combination with module loaders as advertised. - Fixed filesizeformat. - Added a non-silent option for babel extraction. - Added ``urlencode`` filter that automatically quotes values for URL safe usage with utf-8 as only supported encoding. If applications want to change this encoding they can override the filter. - Added ``keep-trailing-newline`` configuration to environments and templates to optionally preserve the final trailing newline. - Accessing ``last`` on the loop context no longer causes the iterator to be consumed into a list. - Python requirement changed: 2.6, 2.7 or >= 3.3 are required now, supported by same source code, using the "six" compatibility library. - Allow ``contextfunction`` and other decorators to be applied to ``__call__``. - Added support for changing from newline to different signs in the ``wordwrap`` filter. - Added support for ignoring memcache errors silently. - Added support for keeping the trailing newline in templates. - Added finer grained support for stripping whitespace on the left side of blocks. - Added ``map``, ``select``, ``reject``, ``selectattr`` and ``rejectattr`` filters. - Added support for ``loop.depth`` to figure out how deep inside a recursive loop the code is. - Disabled py_compile for pypy and python 3. Version 2.6 ----------- (codename Convolution, released on July 24th 2011) - internal attributes now raise an internal attribute error now instead of returning an undefined. This fixes problems when passing undefined objects to Python semantics expecting APIs. - traceback support now works properly for PyPy. (Tested with 1.4) - implemented operator intercepting for sandboxed environments. This allows application developers to disable builtin operators for better security. (For instance limit the mathematical operators to actual integers instead of longs) - groupby filter now supports dotted notation for grouping by attributes of attributes. - scoped blocks now properly treat toplevel assignments and imports. Previously an import suddenly "disappeared" in a scoped block. - automatically detect newer Python interpreter versions before loading code from bytecode caches to prevent segfaults on invalid opcodes. The segfault in earlier Jinja2 versions here was not a Jinja2 bug but a limitation in the underlying Python interpreter. If you notice Jinja2 segfaulting in earlier versions after an upgrade of the Python interpreter you don't have to upgrade, it's enough to flush the bytecode cache. This just no longer makes this necessary, Jinja2 will automatically detect these cases now. - the sum filter can now sum up values by attribute. This is a backwards incompatible change. The argument to the filter previously was the optional starting index which defaults to zero. This now became the second argument to the function because it's rarely used. - like sum, sort now also makes it possible to order items by attribute. - like sum and sort, join now also is able to join attributes of objects as string. - the internal eval context now has a reference to the environment. - added a mapping test to see if an object is a dict or an object with a similar interface. Version 2.5.5 ------------- (re-release of 2.5.4 with built documentation removed for filesize. Released on October 18th 2010) - built documentation is no longer part of release. Version 2.5.4 ------------- (bugfix release, released on October 17th 2010) - Fixed extensions not loading properly with overlays. - Work around a bug in cpython for the debugger that causes segfaults on 64bit big-endian architectures. Version 2.5.3 ------------- (bugfix release, released on October 17th 2010) - fixed an operator precedence error introduced in 2.5.2. Statements like "-foo.bar" had their implicit parentheses applied around the first part of the expression ("(-foo).bar") instead of the more correct "-(foo.bar)". Version 2.5.2 ------------- (bugfix release, released on August 18th 2010) - improved setup.py script to better work with assumptions people might still have from it (``--with-speedups``). - fixed a packaging error that excluded the new debug support. Version 2.5.1 ------------- (bugfix release, released on August 17th 2010) - StopIteration exceptions raised by functions called from templates are now intercepted and converted to undefineds. This solves a lot of debugging grief. (StopIteration is used internally to abort template execution) - improved performance of macro calls slightly. - babel extraction can now properly extract newstyle gettext calls. - using the variable ``num`` in newstyle gettext for something else than the pluralize count will no longer raise a :exc:`KeyError`. - removed builtin markup class and switched to markupsafe. For backwards compatibility the pure Python implementation still exists but is pulled from markupsafe by the Jinja2 developers. The debug support went into a separate feature called "debugsupport" and is disabled by default because it is only relevant for Python 2.4 - fixed an issue with unary operators having the wrong precedence. Version 2.5 ----------- (codename Incoherence, released on May 29th 2010) - improved the sort filter (should have worked like this for a long time) by adding support for case insensitive searches. - fixed a bug for getattribute constant folding. - support for newstyle gettext translations which result in a nicer in-template user interface and more consistent catalogs. (:ref:`newstyle-gettext`) - it's now possible to register extensions after an environment was created. Version 2.4.1 ------------- (bugfix release, released on April 20th 2010) - fixed an error reporting bug for undefineds. Version 2.4 ----------- (codename Correlation, released on April 13th 2010) - the environment template loading functions now transparently pass through a template object if it was passed to it. This makes it possible to import or extend from a template object that was passed to the template. - added a :class:`ModuleLoader` that can load templates from precompiled sources. The environment now features a method to compile the templates from a configured loader into a zip file or folder. - the _speedups C extension now supports Python 3. - added support for autoescaping toggling sections and support for evaluation contexts (:ref:`eval-context`). - extensions have a priority now. Version 2.3.1 ------------- (bugfix release, released on February 19th 2010) - fixed an error reporting bug on all python versions - fixed an error reporting bug on Python 2.4 Version 2.3 ----------- (codename 3000 Pythons, released on February 10th 2010) - fixes issue with code generator that causes unbound variables to be generated if set was used in if-blocks and other small identifier problems. - include tags are now able to select between multiple templates and take the first that exists, if a list of templates is given. - fixed a problem with having call blocks in outer scopes that have an argument that is also used as local variable in an inner frame (#360). - greatly improved error message reporting (#339) - implicit tuple expressions can no longer be totally empty. This change makes ``{% if %}...{% endif %}`` a syntax error now. (#364) - added support for translator comments if extracted via babel. - added with-statement extension. - experimental Python 3 support. Version 2.2.1 ------------- (bugfix release, released on September 14th 2009) - fixes some smaller problems for Jinja2 on Jython. Version 2.2 ----------- (codename Kong, released on September 13th 2009) - Include statements can now be marked with ``ignore missing`` to skip non existing templates. - Priority of ``not`` raised. It's now possible to write `not foo in bar` as an alias to `foo not in bar` like in python. Previously the grammar required parentheses (`not (foo in bar)`) which was odd. - Fixed a bug that caused syntax errors when defining macros or using the `{% call %}` tag inside loops. - Fixed a bug in the parser that made ``{{ foo[1, 2] }}`` impossible. - Made it possible to refer to names from outer scopes in included templates that were unused in the callers frame (#327) - Fixed a bug that caused internal errors if names where used as iteration variable and regular variable *after* the loop if that variable was unused *before* the loop. (#331) - Added support for optional ``scoped`` modifier to blocks. - Added support for line-comments. - Added the ``meta`` module. - Renamed (undocumented) attribute "overlay" to "overlayed" on the environment because it was clashing with a method of the same name. - speedup extension is now disabled by default. Version 2.1.1 ------------- (bugfix release, released on December 25th 2008) - Fixed a translation error caused by looping over empty recursive loops. Version 2.1 ----------- (codename YasuzÅ�, released on November 23rd 2008) - fixed a bug with nested loops and the special loop variable. Before the change an inner loop overwrote the loop variable from the outer one after iteration. - fixed a bug with the i18n extension that caused the explicit pluralization block to look up the wrong variable. - fixed a limitation in the lexer that made ``{{ foo.0.0 }}`` impossible. - index based subscribing of variables with a constant value returns an undefined object now instead of raising an index error. This was a bug caused by eager optimizing. - the i18n extension looks up ``foo.ugettext`` now followed by ``foo.gettext`` if an translations object is installed. This makes dealing with custom translations classes easier. - fixed a confusing behavior with conditional extending. loops were partially executed under some conditions even though they were not part of a visible area. - added ``sort`` filter that works like ``dictsort`` but for arbitrary sequences. - fixed a bug with empty statements in macros. - implemented a bytecode cache system. (:ref:`bytecode-cache`) - the template context is now weakref-able - inclusions and imports "with context" forward all variables now, not only the initial context. - added a cycle helper called ``cycler``. - added a joining helper called ``joiner``. - added a ``compile_expression`` method to the environment that allows compiling of Jinja expressions into callable Python objects. - fixed an escaping bug in urlize Version 2.0 ----------- (codename jinjavitus, released on July 17th 2008) - the subscribing of objects (looking up attributes and items) changed from slightly. It's now possible to give attributes or items a higher priority by either using dot-notation lookup or the bracket syntax. This also changed the AST slightly. ``Subscript`` is gone and was replaced with :class:`~jinja2.nodes.Getitem` and :class:`~jinja2.nodes.Getattr`. For more information see :ref:`the implementation details `. - added support for preprocessing and token stream filtering for extensions. This would allow extensions to allow simplified gettext calls in template data and something similar. - added :meth:`jinja2.environment.TemplateStream.dump`. - added missing support for implicit string literal concatenation. ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}`` - ``else`` is optional for conditional expressions. If not given it evaluates to ``false``. - improved error reporting for undefined values by providing a position. - ``filesizeformat`` filter uses decimal prefixes now per default and can be set to binary mode with the second parameter. - fixed bug in finalizer Version 2.0rc1 -------------- (no codename, released on June 9th 2008) - first release of Jinja2 PKê|>]èÉÇx||$examples/basic/templates/broken.htmlnu„[µü¤PKê|>]”*D @@'Ðexamples/basic/templates/subbroken.htmlnu„[µü¤PKê|>];÷¸gexamples/basic/cycle.pynu„[µü¤PKê|>]›V ßßÃexamples/basic/debugger.pynu„[µü¤PKê|>]Çêâ‚UUìexamples/basic/inheritance.pynu„[µü¤PKê|>]ÚNñddŽexamples/basic/test.pynu„[µü¤PKê|>]oåfN¾¾08examples/basic/test_filter_and_linestatements.pynu„[µü¤PKê|>]½òÉ¿(("V examples/basic/test_loop_filter.pynu„[µü¤PKê|>]�ÙÜ   Ð examples/basic/translate.pynu„[µü¤PKê|>]�¨†ŸDD"'examples/rwbench/django/_form.htmlnu„[µü¤PKê|>]îÞ‡¼@@)½examples/rwbench/django/_input_field.htmlnu„[µü¤PKê|>]Ô€ãWW&Vexamples/rwbench/django/_textarea.htmlnu„[µü¤PKê|>]Ówn¨¨"examples/rwbench/django/index.htmlnu„[µü¤PKê|>]=|†gg#ýexamples/rwbench/django/layout.htmlnu„[µü¤PKê|>]À|Fi……$·examples/rwbench/genshi/helpers.htmlnu„[µü¤PKê|>]ôÚµRÅÅ"�examples/rwbench/genshi/index.htmlnu„[µü¤PKê|>]CÍ�íí#§examples/rwbench/genshi/layout.htmlnu„[µü¤PKê|>]¹ÿ -»»#ç#examples/rwbench/jinja/helpers.htmlnu„[µü¤PKê|>]ðâáw!õ%examples/rwbench/jinja/index.htmlnu„[µü¤PKê|>]J­eúkk"F*examples/rwbench/jinja/layout.htmlnu„[µü¤PKê|>]€iËŒŒ".examples/rwbench/mako/helpers.htmlnu„[µü¤PKê|>]ÆÎÎ á/examples/rwbench/mako/index.htmlnu„[µü¤PKê|>]?i^^!ÿ3examples/rwbench/mako/layout.htmlnu„[µü¤PKê|>]` nƒÚÚ®7examples/rwbench/djangoext.pynu„[µü¤PKê|>]Í'�  ÕFexamples/rwbench/rwbench.pynu„[µü¤PKê|>]Ï+gæª*ª*2Texamples/bench.pynu„[µü¤PKê|>]SAxýSSexamples/profile.pynu„[µü¤PKê|>]‰3ä?³ƒext/Vim/jinja.vimnu„[µü¤PKê|>]ñ3Kèôô%šext/django2jinja/templates/index.htmlnu„[µü¤PKê|>] #|aoo&O ext/django2jinja/templates/layout.htmlnu„[µü¤PKê|>]ÝÝ} +¡ext/django2jinja/templates/subtemplate.htmlnu„[µü¤PKê|>]Q`O|§`§` |¡ext/django2jinja/django2jinja.pynu„[µü¤PKê|>]Ë«  ôôsext/django2jinja/example.pynu„[µü¤PKê|>]·ÛTöµ µ ²ext/djangojinja2.pynu„[µü¤PKê|>]x·_O? ? ªext/inlinegettext.pynu„[µü¤PKê|>]¦ÕÔØ}} -ext/jinja.elnu„[µü¤PKê|>]l6 C@‚@‚æ,html/_sources/api.rst.txtnu„[µü¤PKê|>]‡øÐ.00o¯html/_sources/changelog.rst.txtnu„[µü¤PKê|>]yL9æ+æ+ î¯html/_sources/extensions.rst.txtnu„[µü¤PKê|>]JÊ z··$Ühtml/_sources/faq.rst.txtnu„[µü¤PKê|>])ˆõ™ãã$ühtml/_sources/index.rst.txtnu„[µü¤PKê|>]×´Œ í í !Rhtml/_sources/integration.rst.txtnu„[µü¤PKê|>]z½z>>�html/_sources/intro.rst.txtnu„[µü¤PKê|>]§?@YSS html/_sources/latexindex.rst.txtnu„[µü¤PKê|>]9’Ú!¼html/_sources/nativetypes.rst.txtnu„[µü¤PKê|>]M`™Ð Ð *&html/_sources/sandbox.rst.txtnu„[µü¤PKê|>]DgXm››G4html/_sources/switching.rst.txtnu„[µü¤PKê|>]:õ³¯ Õ Õ1Phtml/_sources/templates.rst.txtnu„[µü¤PKê|>]¤²Ü›� � Œ%html/_sources/tricks.rst.txtnu„[µü¤PKê|>]<>¡¡e2html/_static/ajax-loader.gifnu„[µü¤PKê|>] Д)Ü)Ü)R5html/_static/basic.cssnu„[µü¤PKê|>]x,Ëôôt_html/_static/comment-bright.pngnu„[µü¤PKê|>]5†ú==·bhtml/_static/comment-close.pngnu„[µü¤PKê|>]4³ÿ ��Bfhtml/_static/comment.pngnu„[µü¤PKê|>]JOžS$$ ihtml/_static/doctools.jsnu„[µü¤PKê|>]>¾ta%[�html/_static/documentation_options.jsnu„[µü¤PKê|>]„'»ÞÞÄŽhtml/_static/down-pressed.pngnu„[µü¤PKê|>]9.¡ÂÊÊï�html/_static/down.pngnu„[µü¤PKê|>]S[¯Sþ�html/_static/file.pngnu„[µü¤PKê|>]5Qçô(ô(a’html/_static/jinja-small.pngnu„[µü¤PKê|>]ä¬YÇcc¡»html/_static/jinja.cssnu„[µü¤PKê|>]�¥ÌØJÔhtml/_static/jquery-3.2.1.jsnu„[µü¤PKê|>])ÿƒRƒR�ëhtml/_static/jquery.jsnu„[µü¤PKê|>]‘µ°ZZf> html/_static/minus.pngnu„[µü¤PKê|>]ÑÒ%ZZZ? html/_static/plus.pngnu„[µü¤PKê|>]&9‘µµ¥? html/_static/pygments.cssnu„[µü¤PKê|>]†º�Úicic£N html/_static/searchtools.jsnu„[µü¤PKê|>]†ó‚®`‰`‰ W² html/_static/underscore-1.3.1.jsnu„[µü¤PKê|>]šš;ÿl/l/< html/_static/underscore.jsnu„[µü¤PKê|>]ÿ·�HÖÖ½k html/_static/up-pressed.pngnu„[µü¤PKê|>]>uËýËËÞl html/_static/up.pngnu„[µü¤PKê|>]Fo,¼ c cìm html/_static/websupport.jsnu„[µü¤PKê|>]Rä&˜Ã˜Ã AÑ html/api.htmlnu„[µü¤PKê|>]ÙÇ‘a…·…·• html/changelog.htmlnu„[µü¤PKê|>]'1xŠÇõÇõÞLhtml/extensions.htmlnu„[µü¤PKê|>]a—Š#‘E‘E éBhtml/faq.htmlnu„[µü¤PKê|>]ÀRïu½­½­·ˆhtml/genindex.htmlnu„[µü¤PKê|>]¢W˜ˆ;N;N¶6html/index.htmlnu„[µü¤PKê|>]ÄU  ) )0…html/integration.htmlnu„[µü¤PKê|>]ÀsÁ§0§0�®html/intro.htmlnu„[µü¤PKê|>]¡i$´ÝBÝBgßhtml/latexindex.htmlnu„[µü¤PKê|>]�>4éC1C1ˆ"html/nativetypes.htmlnu„[µü¤PKê|>]QÎñ†ß ß Thtml/objects.invnu„[µü¤PKê|>]ï* ³UU/ahtml/py-modindex.htmlnu„[µü¤PKê|>]"…z92f2fÉqhtml/sandbox.htmlnu„[µü¤PKê|>]¤žmëê ê <Øhtml/search.htmlnu„[µü¤PKê|>]�J¡¬Œ™Œ™fåhtml/searchindex.jsnu„[µü¤PKê|>]FÏ^þ‰R‰R5html/switching.htmlnu„[µü¤PKê|>]Ð40tßGßGÒhtml/templates.htmlnu„[µü¤PKê|>]hm-7::#html/tricks.htmlnu„[µü¤PKê|>]î£ç[OOeTAUTHORSnu„[µü¤PKê|>]ÚÆ9ã^ã^ ëVCHANGES.rstnu„[µü¤PK\\u ¶