U aa6@s dZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl m Z ddl mZddl mZd d lmZd d lmZd d lmZd d lmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlm Z ej!rjddl"Z#d dl$m%Z%d dl&m'Z'd dlm(Z(d dl)m*Z*Gddde#j+Z,ej-dej.dej/fdZ0e-d Z1e-d!Z2e0e0d"d#d$Z3e0e0d"d%d&Z4e0e0d"d'd(Z5e2e2d)d*d+Z6dd,ej7ej8e9e:fej7ej.ej/gej/fej7ej/ej.ej/gej/fd-d.d/Z;dd,ej7ej8e9e:fej7ej.ej/gej/fej.ej/gejd6ed)d7d8Z?ej8e9ej@e9ej/fejAejBe9ej/ffe9d)d9d:ZCedd;e9e9e9ej7e:e9d<d=d>ZDe9e9d?d@dAZEe9e9d?dBdCZFedd;ej@e9ej/feGe9dEdFdGZHe9e9d?dHdIZIeJdJZKe9e9d?dKdLZLdej@e1e2feGdOeGej.attrgetter)_prepare_attribute_partsr<Any)rArBrCrDrKr"rIr%make_attrgetterls  rN)rArBrCr csPt|tr|d}n|g}dd|Dtjtjtjdfdd }|S)aReturns a callable that looks up the given comma separated attributes from a passed object with the rules of the environment. Dots are allowed to access attributes of each attribute. Integer parts in paths are looked up as integers. The value returned by the returned callable is a list of extracted attribute values. Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc. ,cSsg|] }t|qSr")rL.0rFr"r"r% sz)make_multi_attrgetter..rEcsVdgt}tD]:\}}|}|D]}||}q&dk rH|}|||<q|Sr!)len enumeraterG)rFitemsiZattribute_partZitem_irHrArJrCr"r%rKs z)make_multi_attrgetter..attrgetter)r;r*splitr<rMList)rArBrCrXrKr"rWr%make_multi_attrgetters   "rZ)attrr cCs0|dkr gSt|tr*dd|dDS|gS)NcSs g|]}|rt|n|qSr")isdigitint)rQxr"r"r%rRsz,_prepare_attribute_parts...)r;r*rX)r[r"r"r%rLs  rLzt.Union[str, HasHTML]cCs&t|drtd|}tt|S)zCEnforce HTML escaping. This will probably double escape variables.r&r)hasattrr<r=r&rr*r?r"r"r%do_forceescapes racCsJt|tst|tjst|St|tr2|}n|}ddd|DS)a3Quote data for use in a URL path or query using UTF-8. Basic wrapper around :func:`urllib.parse.quote` when given a string, or :func:`urllib.parse.urlencode` for a dict or iterable. :param value: Data to quote. A string will be quoted directly. A dict or iterable of ``(key, value)`` pairs will be joined as a query string. When given a string, "/" is not quoted. HTTP servers treat "/" and "%2F" equivalently in paths. If you need quoted slashes, use the ``|replace("/", "%2F")`` filter. .. versionadded:: 2.7 &css0|](\}}t|dddt|ddVqdS)T)Zfor_qs=Nr)rQkvr"r"r% szdo_urlencode..)r;r*rIterablerdictrUjoin)r:rUr"r"r% do_urlencodes   rjr)eval_ctxsoldnewcountr cCsr|dkr d}|js,t|t|t||St|dsJt|drTt|dsTt|}nt|}|t|t||S)aReturn 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: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh Nr&) autoescaper*replacer`rr)rkrlrmrnror"r"r% do_replaces rs)rlr cCs t|S)zConvert a value to uppercase.)rupperrlr"r"r%do_uppersrvcCs t|S)zConvert a value to lowercase.)rr>rur"r"r%do_lower srwT)rkd autospacer cCs:ddd|D}|r(|r(d|}|jr6t|}|S)acCreate an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja ... Results in something like this: .. sourcecode:: html
    ...
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.  css<|]4\}}|dk rt|tst|dt|dVqdS)Nz="")r;rr)rQkeyr:r"r"r%rf,s zdo_xmlattr..)rirUrqr)rkrxryrvr"r"r% do_xmlattrs r~cCs t|S)zYCapitalize a value. The first character will be uppercase, all others lowercase. )r capitalizerur"r"r% do_capitalize;srz ([-\s({\[<]+)cCsdddtt|DS)zReturn a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. cSs,g|]$}|r|d|ddqS)rr N)rtr>rPr"r"r%rRJszdo_title..)ri_word_beginning_split_rerXrrur"r"r%do_titleEs  rFr|zte.Literal["key", "value"])r:case_sensitivebyreverser cs\|dkrdn|dkrdntdtjtjtjftjdfdd }t|||d S) afSort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first. .. sourcecode:: jinja {% for key, value in mydict|dictsort %} sort the dict by key, case insensitive {% for key, value in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for key, value in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for key, value in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive r|rr:r z,You can only sort by either "key" or "value"rEcs|}st|}|Sr!)r@)rFr:rposr"r% sort_funcpszdo_dictsort..sort_funcr|r)rr<TuplerMsortedrU)r:rrrrr"rr% do_dictsortRs&rz t.Iterable[V]z t.List[V])rAr:rrrBr cCs$t|||stndd}t|||dS)a*Sort an iterable using Python's :func:`sorted`. .. sourcecode:: jinja {% for city in cities|sort %} ... {% endfor %} :param reverse: Sort descending instead of ascending. :param case_sensitive: When sorting strings, sort upper and lower case separately. :param attribute: When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like ``"address.city"``. Can be a list of attributes like ``"age,name"``. The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible to chain sorts on different attributes and ordering. .. sourcecode:: jinja {% for user in users|sort(attribute="name") |sort(reverse=true, attribute="age") %} ... {% endfor %} As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes. .. sourcecode:: jinja {% for user users|sort(attribute="age,name") %} ... {% endfor %} .. versionchanged:: 2.11.0 The ``attribute`` parameter can be a comma separated list of attributes, e.g. ``"age,name"``. .. versionchanged:: 2.6 The ``attribute`` parameter was added. NrCr)rZr@r)rAr:rrrBkey_funcr"r"r%do_sort{s 2 rz t.Iterator[V])rAr:rrBr ccsJt|||stndd}t}|D]$}||}||kr |||Vq dS)aReturns a list of unique items from the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. Nr)rNr@setadd)rAr:rrBgetterseenrFr|r"r"r% do_uniques  rzt.Callable[..., V]zt.Union[V, Undefined])rAr:funcrrBr cCs^t|}z t|}Wntk r2|dYSXt|||sBtndd}|t|g||dS)Nz'No aggregated item, sequence was empty.rr|)iternext StopIteration undefinedrNr@r)rAr:rrrBitfirstrr"r"r% _min_or_maxs  rcCst||t||S)aReturn the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the min value of this attribute. )rminrAr:rrBr"r"r%do_minsrcCst||t||S)aReturn the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. )rmaxrr"r"r%do_maxsrr)r: default_valuebooleanr cCst|ts|r|s|S|S)a`If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ 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`: .. sourcecode:: jinja {{ ''|default('the string was empty', true) }} .. versionchanged:: 2.11 It's now possible to configure the :class:`~jinja2.Environment` with :class:`~jinja2.ChainableUndefined` to make the `default` filter work on nested elements and attributes that may contain undefined values in the chain without getting an :exc:`~jinja2.UndefinedError`. )r;r)r:rrr"r"r% do_defaultsr)rkr:rxrBr cCs|dk rtt|j||}|js4t|tt|St|dst|}d}t|D]$\}}t|drjd}qRt|||<qR|rt |}nt|}||St |tt |S)a#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: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. Nr&FT) maprNrArqr*rir`listrTrr)rkr:rxrBZ do_escapeidxrFr"r"r% sync_do_join1s     rcst|t|IdH||Sr!)rr)rkr:rxrBr"r"r%do_joinksrP)r:widthr cCst||S)z.Centers the value in a field of a given width.)rcenter)r:rr"r"r% do_centerusr)rAseqr cCs2ztt|WStk r,|dYSXdS)z$Return the first item of a sequence."No first item, sequence was empty.N)rrrrrArr"r"r% sync_do_firstzsrz*t.Union[t.AsyncIterable[V], t.Iterable[V]]cs8zt|IdHWStk r2|dYSXdS)Nr)r __anext__StopAsyncIterationrrr"r"r%do_firstsrzt.Reversible[V]cCs6zttt|WStk r0|dYSXdS)zReturn the last item of a sequence. Note: Does not work with generators. You may want to explicitly convert it to a list: .. sourcecode:: jinja {{ data | selectattr('name', '==', 'Jinja') | list | last }} z!No last item, sequence was empty.N)rrreversedrrrr"r"r%do_lasts rrz t.Sequence[V])contextrr cCs2z t|WStk r,|jdYSXdS)z'Return a random item from the sequence.z#No random item, sequence was empty.N)randomchoice IndexErrorrAr)rrr"r"r% do_randoms r)r:binaryr cCst|}|rdnd}|rdnd|r&dnd|r0dnd|r:d nd |rDd nd |rNd nd|rXdnd|rbdndg}|dkrtdS||krt|dSt|D]8\}}||d}||kr|||dd|Sq|||dd|SdS)zFormat 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). iiZKiBZkBZMiBZMBZGiBZGBZTiBZTBZPiBZPBZEiBZEBZZiBZZBZYiBZYBr z1 Bytez Bytesr0z.1frzN)floatr]rT)r:rbytesbaseprefixesrVprefixunitr"r"r%do_filesizeformats(           rcCst|S)z.Pretty print a variable. Useful for debugging.rr?r"r"r% do_pprintsrz^([\w.+-]{2,}:(/){0,2})$)rkr:trim_url_limitnofollowtargetrel extra_schemesr c Cs|jj}t|pd}|r&|d||dp4ddt|pLd}|dkr^|d}|dkrr|dppd}|D] } t | dkrvt | d qvt |||||d } |j rt | } | S) a0Convert URLs in text into clickable links. This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a Markdown library, is a better choice. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email addresses. Links with trailing punctuation (periods, commas, closing parentheses) and leading punctuation (opening parentheses) are recognized excluding the punctuation. Email addresses that include header fields are not recognized (for example, ``mailto:address@example.com?cc=copy@example.com``). :param value: Original text containing URLs to link. :param trim_url_limit: Shorten displayed URL values to this length. :param nofollow: Add the ``rel=nofollow`` attribute to links. :param target: Add the ``target`` attribute to links. :param rel: Add the ``rel`` attribute to links. :param extra_schemes: Recognize URLs that start with these schemes in addition to the default behavior. Defaults to ``env.policies["urlize.extra_schemes"]``, which defaults to no extra schemes. .. versionchanged:: 3.0 The ``extra_schemes`` parameter was added. .. versionchanged:: 3.0 Generate ``https://`` links for URLs without a scheme. .. versionchanged:: 3.0 The parsing rules were updated. Recognize email addresses with or without the ``mailto:`` scheme. Validate IP addresses. Ignore parentheses and brackets in more cases. .. versionchanged:: 2.8 The ``target`` parameter was added. rrz urlize.relrzNz urlize.targetzurlize.extra_schemesr"z" is not a valid URI scheme prefix.)rrrr)rApoliciesrrXrupdaterir_uri_scheme_re fullmatchrrrqr) rkr:rrrrrrZ rel_partsschemer}r"r"r% do_urlizes./  r)rlrrblankr cst|tr|nd|d}t|tr6tt|}||7}|rV||}n6|}|d}|r|||fdd|D7}|r|}|S)aReturn a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces, or a string, to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 3.0 ``width`` can be a string. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. rz rc3s|]}|r|n|VqdSr!r"rQlineZ indentionr"r%rfMszdo_indent..)r;r*rri splitlinespop)rlrrrnewliner}linesr"rr% do_indent's&    r...)envrllength killwordsendleewayr cCs|dkr|jd}|t|ks6tdt|d||dksLtd|t|||kr`|S|r||d|t||S|d|t|ddd}||S) aReturn 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. .. sourcecode:: jinja {{ "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 Jinja versions is 5 and was 0 before but can be reconfigured globally. Nztruncate.leewayzexpected length >= z, got rzexpected leeway >= 0, got rzr )rrSAssertionErrorrsplit)rrlrrrrresultr"r"r% do_truncateWs  $ rO)rArlrbreak_long_words wrapstringbreak_on_hyphensr cs:ddldkr|jfdd|DS)aWrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately. :param s: Original text to wrap. :param width: Maximum length of wrapped lines. :param break_long_words: If a word is longer than ``width``, break it across lines. :param break_on_hyphens: If a word contains hyphens, it may be split across lines. :param wrapstring: String to join each wrapped line. Defaults to :attr:`Environment.newline_sequence`. .. versionchanged:: 2.11 Existing newlines are treated as paragraphs wrapped separately. .. versionchanged:: 2.11 Added the ``break_on_hyphens`` parameter. .. versionchanged:: 2.7 Added the ``wrapstring`` parameter. rNc s(g|] }j|dddqS)F)r expand_tabsreplace_whitespacerr)riwraprrrtextwraprrr"r%rRs zdo_wordwrap..)rZnewline_sequencerir)rArlrrrrr"rr% do_wordwraps rz\w+cCsttt|S)zCount the words in that string.)rS_word_refindallrrur"r"r% do_wordcountsr )r:rDrr c Csrz t|trt||WSt|WSttfk rlztt|WYSttfk rf|YYSXYnXdS)aConvert 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. N)r;r*r] TypeError ValueErrorr)r:rDrr"r"r%do_ints    r)r:rDr c Cs,z t|WSttfk r&|YSXdS)zConvert 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. N)rrr)r:rDr"r"r%do_floats r)r:argskwargsr cOs |r|rtdt||p|S)aApply the given values to a `printf-style`_ format string, like ``string % values``. .. sourcecode:: jinja {{ "%s, %s!"|format(greeting, name) }} Hello, World! In most cases it should be more convenient and efficient to use the ``%`` operator or :meth:`str.format`. .. code-block:: text {{ "%s, %s!" % (greeting, name) }} {{ "{}, {}!".format(greeting, name) }} .. _printf-style: https://docs.python.org/library/stdtypes.html #printf-style-string-formatting z>can't handle positional and keyword arguments at the same time)rr)r:rrr"r"r% do_formats r)r:charsr cCst||S)z=Strip leading and trailing characters, by default whitespace.)rstrip)r:rr"r"r%do_trimsrcCs*t|drtd|}tt|S)zAStrip SGML/XML tags and replace adjacent whitespace by one space.r&r)r`r<r=r&rr* striptagsr?r"r"r% do_striptags s rzt.Collection[V]z t.Optional[V]zt.Iterator[t.List[V]])r:slices fill_withr c cst|}t|}||}||}d}t|D]\}|||} ||krL|d7}||d|} || | } |dk r||kr| || Vq,dS)aFSlice 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: .. sourcecode:: html+jinja
{%- for column in items|slice(3) %}
    {%- for item in column %}
  • {{ item }}
  • {%- endfor %}
{%- endfor %}
If you pass it a second argument it's used to fill missing values on the last iteration. rr N)rrSrangeappend) r:rrrrZitems_per_sliceZslices_with_extraoffsetZ slice_numberstartrtmpr"r"r% sync_do_slices    r cstt|IdH||Sr!)r r)r:rrr"r"r%do_slice<sr )r: linecountrr ccsfg}|D]$}t||kr"|Vg}||q|rb|dk r\t||kr\||g|t|7}|VdS)a  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: .. sourcecode:: html+jinja {%- for row in items|batch(3, ' ') %} {%- for column in row %} {%- endfor %} {%- endfor %}
{{ column }}
N)rSr)r:r rr rFr"r"r%do_batchEs  r commonz%te.Literal["common", "ceil", "floor"])r: precisionmethodr cCsL|dkrtd|dkr"t||Stt|}tt||d|d|S)aRound 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. .. sourcecode:: jinja {{ 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`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 >ceilfloorrz$method must be common, ceil or floorrr)rroundgetattrmathr<r=r)r:rrrr"r"r%do_roundjs   rc@s>eZdZUejed<ejed<edddZedddZ dS) _GroupTupleZgrouperrrcCs t|Sr!)tuple__repr__r#r"r"r%rsz_GroupTuple.__repr__cCs t|Sr!)r__str__r#r"r"r%rsz_GroupTuple.__str__N) r'r(r)r<rM__annotations__rYr*rrr"r"r"r%rs   rz!t.List[t.Tuple[t.Any, t.List[V]]])rAr:rBrDr cCs*t|||d}ddtt||d|DS)a>Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value. For example, a list of ``User`` objects with a ``city`` attribute can be rendered in groups. In this example, ``grouper`` refers to the ``city`` value of the group. .. sourcecode:: html+jinja
    {% for city, items in users|groupby("city") %}
  • {{ city }}
      {% for user in items %}
    • {{ user.name }} {% endfor %}
  • {% endfor %}
``groupby`` yields namedtuples of ``(grouper, list)``, which can be used instead of the tuple unpacking above. ``grouper`` is the value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja
    {% for group in users|groupby("city") %}
  • {{ group.grouper }}: {{ group.list|join(", ") }} {% endfor %}
You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja
    {% for city, items in users|groupby("city", default="NY") %}
  • {{ city }}: {{ items|map(attribute="name")|join(", ") }}
  • {% endfor %}
.. versionchanged:: 3.0 Added the ``default`` parameter. .. versionchanged:: 2.6 The attribute supports dot notation for nested access. rDcSsg|]\}}t|t|qSr")rrrQr|valuesr"r"r%rRsz#sync_do_groupby..r)rNrrrAr:rBrDexprr"r"r%sync_do_groupbys4r!cs:t|||d}ddttt|IdH|d|DIdHS)Nrcs$g|]\}}t|t|IdHqSr!)rrrr"r"r%rRszdo_groupby..r)rNrrrrr"r"r% do_groupbysr")rAiterablerBrr cCs"|dk rtt|||}t||S)aReturns 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: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right. N)rrNsum)rAr#rBrr"r"r% sync_do_sumsr%csP|}|dk rt||}nttddd}t|2z3dHW}|||7}q06|S)Nr^r cSs|Sr!r"r^r"r"r%rszdo_sum..func)rNr.r )rAr#rBrr}rrFr"r"r%do_sums r(cCst|S)zkConvert the value into a list. If it was a string the returned list will be a list of characters. )rr?r"r"r% sync_do_listsr)cst|IdHSr!r r?r"r"r%do_list sr*cCst|S)zMark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. rr?r"r"r% do_mark_safe%sr+cCst|S)zHMark a value as unsafe. This is the reverse operation for :func:`safe`.)r*r?r"r"r%do_mark_unsafe,sr,cCsdSr!r"r?r"r"r% do_reverse1sr-cCsdSr!r"r?r"r"r%r-6sc Cstt|tr|dddSz t|WStk rnzt|}||WYStk rhtdYnXYnXdS)z\Reverse the object or return an iterator that iterates over it the other way round. Nrpzargument must be iterable)r;r*rrrrr)r:r}r"r"r%r-;s   )rAobjnamer cCsz t|}Wntk r YnVXzt||}Wntk rDYn2X|jrrtd|}||||sr|||S|S|j ||dS)zGet an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions ` for more details. r)r.r/) r* UnicodeErrorrAttributeErrorZ sandboxedr<r=Zis_safe_attributeZunsafe_undefinedr)rAr.r/r:r"r"r%do_attrMs    r2)rr:r/rrr cOsdSr!r"rr:r/rrr"r"r% sync_do_maplsr4)rBrD)rr:rBrDr cCsdSr!r"rr:rBrDr"r"r%r4ss)rr:rrr cos(|r$t|||}|D]}||VqdS)aApplies 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: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja {{ users|map(attribute="username", default="Anonymous")|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: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} Similar to a generator comprehension such as: .. code-block:: python (u.username for u in users) (getattr(u, "username", "Anonymous") for u in users) (do_lower(x) for x in titles) .. versionchanged:: 2.11.0 Added the ``default`` parameter. .. versionadded:: 2.7 N) prepare_maprr:rrrrFr"r"r%r4~s+ cOsdSr!r"r3r"r"r%do_mapsr8cCsdSr!r"r5r"r"r%r8scOs@|rz sync_do_select..Fselect_or_rejectrr:rrr"r"r%sync_do_selectsr>zt.AsyncIterator[V]cst||||dddS)NcSs|Sr!r"r'r"r"r%r9r:zdo_select..Fasync_select_or_rejectr=r"r"r% do_selectsrAcOst||||dddS)aFilters 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: .. sourcecode:: jinja {{ numbers|reject("odd") }} Similar to a generator comprehension such as: .. code-block:: python (n for n in numbers if not test_odd(n)) .. versionadded:: 2.7 cSs| Sr!r"r'r"r"r%r9r:z sync_do_reject..Fr;r=r"r"r%sync_do_rejectsrBcst||||dddS)NcSs| Sr!r"r'r"r"r%r9r:zdo_reject..Fr?r=r"r"r% do_rejectsrCcOst||||dddS)aWFilters 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: .. sourcecode:: jinja {{ users|selectattr("is_active") }} {{ users|selectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if user.is_active) (u for user in users if test_none(user.email)) .. versionadded:: 2.7 cSs|Sr!r"r'r"r"r%r9<r:z$sync_do_selectattr..Tr;r=r"r"r%sync_do_selectattr!srDcst||||dddS)NcSs|Sr!r"r'r"r"r%r9Fr:zdo_selectattr..Tr?r=r"r"r% do_selectattr?srEcOst||||dddS)aFFilters 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. .. sourcecode:: jinja {{ users|rejectattr("is_active") }} {{ users|rejectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if not user.is_active) (u for user in users if not test_none(user.email)) .. versionadded:: 2.7 cSs| Sr!r"r'r"r"r%r9br:z$sync_do_rejectattr..Tr;r=r"r"r%sync_do_rejectattrIsrFcst||||dddS)NcSs| Sr!r"r'r"r"r%r9lr:zdo_rejectattr..Tr?r=r"r"r% do_rejectattresrG)rkr:indentr cCsD|jj}|d}|d}|dk r0|}||d<t|fd|i|S)aSerialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents. The returned string is safe to render in HTML documents and ``