python-liquid 2.3.6__py3-none-any.whl → 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. liquid/__about__.py +1 -0
  2. liquid/__init__.py +161 -187
  3. liquid/_base_tag.py +66 -0
  4. liquid/{utils/chain_map.py → _chain_map.py} +18 -19
  5. liquid/_context.py +465 -0
  6. liquid/_drop.py +108 -0
  7. liquid/_filter.py +174 -0
  8. liquid/_io.py +18 -0
  9. liquid/_lax_parser_mixin.py +100 -0
  10. liquid/_lexer.py +93 -0
  11. liquid/_lexer_extended.py +623 -0
  12. liquid/_lexer_legacy.py +536 -0
  13. liquid/_loader.py +84 -0
  14. liquid/{utils/lru_cache.py → _lru_cache.py} +28 -36
  15. liquid/_markup.py +253 -0
  16. liquid/_messages.py +292 -0
  17. liquid/_missing.py +3 -0
  18. liquid/_nothing.py +28 -0
  19. liquid/_parser.py +460 -0
  20. liquid/_parser_extended.py +293 -0
  21. liquid/_parser_legacy.py +819 -0
  22. liquid/_resource_limits.py +50 -0
  23. liquid/_slice.py +41 -0
  24. liquid/_static_analysis.py +503 -0
  25. liquid/_strftime.py +186 -0
  26. liquid/_template.py +536 -0
  27. liquid/drops/__init__.py +20 -0
  28. liquid/drops/forloop.py +78 -0
  29. liquid/drops/iterable.py +25 -0
  30. liquid/drops/range.py +76 -0
  31. liquid/drops/self_.py +45 -0
  32. liquid/drops/tablerowloop.py +142 -0
  33. liquid/drops/undefined.py +228 -0
  34. liquid/environment.py +717 -551
  35. liquid/exceptions.py +67 -214
  36. liquid/expressions.py +1184 -0
  37. liquid/filters/__init__.py +134 -0
  38. liquid/filters/abs.py +7 -0
  39. liquid/filters/append.py +5 -0
  40. liquid/filters/at_least.py +9 -0
  41. liquid/filters/at_most.py +9 -0
  42. liquid/filters/babel.py +560 -0
  43. liquid/filters/base64.py +26 -0
  44. liquid/filters/capitalize.py +5 -0
  45. liquid/filters/ceil.py +8 -0
  46. liquid/filters/compact.py +25 -0
  47. liquid/filters/concat.py +11 -0
  48. liquid/filters/date.py +27 -0
  49. liquid/filters/default.py +25 -0
  50. liquid/filters/divided_by.py +21 -0
  51. liquid/filters/downcase.py +5 -0
  52. liquid/filters/escape.py +56 -0
  53. liquid/filters/find.py +56 -0
  54. liquid/filters/first.py +19 -0
  55. liquid/filters/floor.py +8 -0
  56. liquid/filters/html.py +23 -0
  57. liquid/filters/index.py +12 -0
  58. liquid/filters/join.py +13 -0
  59. liquid/filters/json_.py +30 -0
  60. liquid/filters/last.py +17 -0
  61. liquid/filters/map.py +5 -0
  62. liquid/filters/minus.py +13 -0
  63. liquid/filters/modulo.py +18 -0
  64. liquid/filters/newline_to_br.py +16 -0
  65. liquid/filters/plus.py +13 -0
  66. liquid/filters/prepend.py +5 -0
  67. liquid/filters/reject.py +19 -0
  68. liquid/filters/remove.py +36 -0
  69. liquid/filters/replace.py +32 -0
  70. liquid/filters/reverse.py +5 -0
  71. liquid/filters/round.py +35 -0
  72. liquid/filters/size.py +25 -0
  73. liquid/filters/slice.py +39 -0
  74. liquid/filters/sort.py +148 -0
  75. liquid/filters/split.py +34 -0
  76. liquid/filters/squish.py +9 -0
  77. liquid/filters/strip.py +13 -0
  78. liquid/filters/strip_html.py +19 -0
  79. liquid/filters/strip_newlines.py +17 -0
  80. liquid/filters/sum.py +21 -0
  81. liquid/filters/times.py +13 -0
  82. liquid/filters/translate.py +380 -0
  83. liquid/filters/truncate.py +39 -0
  84. liquid/filters/uniq.py +11 -0
  85. liquid/filters/upcase.py +5 -0
  86. liquid/filters/url.py +18 -0
  87. liquid/filters/where.py +18 -0
  88. liquid/loaders/__init__.py +17 -0
  89. liquid/loaders/caching_file_system_loader.py +64 -0
  90. liquid/loaders/choice_loader.py +93 -0
  91. liquid/loaders/dict_loader.py +56 -0
  92. liquid/{builtin/loaders → loaders}/file_system_loader.py +51 -55
  93. liquid/{builtin/loaders → loaders}/mixins.py +39 -51
  94. liquid/loaders/package_loader.py +110 -0
  95. liquid/tags/__init__.py +61 -0
  96. liquid/tags/assign.py +68 -0
  97. liquid/tags/capture.py +83 -0
  98. liquid/tags/case.py +199 -0
  99. liquid/tags/comment.py +56 -0
  100. liquid/tags/cycle.py +131 -0
  101. liquid/tags/decrement.py +55 -0
  102. liquid/tags/doc.py +56 -0
  103. liquid/tags/echo.py +65 -0
  104. liquid/tags/else_.py +53 -0
  105. liquid/tags/error.py +51 -0
  106. liquid/tags/extends.py +448 -0
  107. liquid/tags/for_.py +421 -0
  108. liquid/tags/if_.py +156 -0
  109. liquid/tags/ifchanged.py +69 -0
  110. liquid/tags/include.py +223 -0
  111. liquid/tags/increment.py +55 -0
  112. liquid/tags/inline_comment.py +70 -0
  113. liquid/tags/liquid.py +56 -0
  114. liquid/tags/macro.py +281 -0
  115. liquid/tags/output.py +58 -0
  116. liquid/tags/raw.py +60 -0
  117. liquid/tags/render.py +245 -0
  118. liquid/tags/tablerow.py +254 -0
  119. liquid/tags/template_comment.py +56 -0
  120. liquid/tags/translate.py +316 -0
  121. liquid/tags/unless.py +121 -0
  122. liquid/tags/with_.py +83 -0
  123. liquid/tokens.py +370 -0
  124. {python_liquid-2.3.6.dist-info → python_liquid-3.0.0.dist-info}/METADATA +32 -39
  125. python_liquid-3.0.0.dist-info/RECORD +128 -0
  126. {python_liquid-2.3.6.dist-info → python_liquid-3.0.0.dist-info}/WHEEL +1 -1
  127. {python_liquid-2.3.6.dist-info → python_liquid-3.0.0.dist-info}/licenses/LICENSE +1 -1
  128. liquid/analyze_tags.py +0 -214
  129. liquid/ast.py +0 -252
  130. liquid/builtin/__init__.py +0 -203
  131. liquid/builtin/content.py +0 -41
  132. liquid/builtin/drops/__init__.py +0 -3
  133. liquid/builtin/drops/drops.py +0 -13
  134. liquid/builtin/expressions/__init__.py +0 -47
  135. liquid/builtin/expressions/_tokenize.py +0 -186
  136. liquid/builtin/expressions/arguments.py +0 -207
  137. liquid/builtin/expressions/filtered.py +0 -387
  138. liquid/builtin/expressions/logical.py +0 -672
  139. liquid/builtin/expressions/loop.py +0 -275
  140. liquid/builtin/expressions/path.py +0 -163
  141. liquid/builtin/expressions/primitive.py +0 -417
  142. liquid/builtin/filters/__init__.py +0 -0
  143. liquid/builtin/filters/array.py +0 -329
  144. liquid/builtin/filters/extra.py +0 -83
  145. liquid/builtin/filters/math.py +0 -129
  146. liquid/builtin/filters/misc.py +0 -137
  147. liquid/builtin/filters/string.py +0 -416
  148. liquid/builtin/illegal.py +0 -28
  149. liquid/builtin/loaders/__init__.py +0 -0
  150. liquid/builtin/loaders/caching_file_system_loader.py +0 -61
  151. liquid/builtin/loaders/choice_loader.py +0 -94
  152. liquid/builtin/loaders/dict_loader.py +0 -64
  153. liquid/builtin/loaders/package_loader.py +0 -132
  154. liquid/builtin/output.py +0 -74
  155. liquid/builtin/tags/__init__.py +0 -0
  156. liquid/builtin/tags/assign_tag.py +0 -75
  157. liquid/builtin/tags/capture_tag.py +0 -98
  158. liquid/builtin/tags/case_tag.py +0 -287
  159. liquid/builtin/tags/comment_tag.py +0 -77
  160. liquid/builtin/tags/cycle_tag.py +0 -132
  161. liquid/builtin/tags/decrement_tag.py +0 -59
  162. liquid/builtin/tags/doc_tag.py +0 -68
  163. liquid/builtin/tags/echo_tag.py +0 -45
  164. liquid/builtin/tags/for_tag.py +0 -337
  165. liquid/builtin/tags/if_tag.py +0 -209
  166. liquid/builtin/tags/ifchanged_tag.py +0 -94
  167. liquid/builtin/tags/include_tag.py +0 -251
  168. liquid/builtin/tags/increment_tag.py +0 -60
  169. liquid/builtin/tags/inline_comment_tag.py +0 -47
  170. liquid/builtin/tags/liquid_tag.py +0 -183
  171. liquid/builtin/tags/render_tag.py +0 -371
  172. liquid/builtin/tags/tablerow_tag.py +0 -320
  173. liquid/builtin/tags/unless_tag.py +0 -218
  174. liquid/context.py +0 -615
  175. liquid/expression.py +0 -41
  176. liquid/extra/__init__.py +0 -98
  177. liquid/extra/filters/__init__.py +0 -33
  178. liquid/extra/filters/_json.py +0 -33
  179. liquid/extra/filters/array.py +0 -60
  180. liquid/extra/filters/babel.py +0 -552
  181. liquid/extra/filters/html.py +0 -32
  182. liquid/extra/filters/translate.py +0 -448
  183. liquid/extra/tags/__init__.py +0 -17
  184. liquid/extra/tags/_with.py +0 -80
  185. liquid/extra/tags/extends_tag.py +0 -576
  186. liquid/extra/tags/macro_tag.py +0 -270
  187. liquid/extra/tags/snippet_tag.py +0 -107
  188. liquid/extra/tags/translate_tag.py +0 -388
  189. liquid/filter.py +0 -230
  190. liquid/future/__init__.py +0 -3
  191. liquid/future/environment.py +0 -30
  192. liquid/future/filters/__init__.py +0 -1
  193. liquid/future/tags/__init__.py +0 -1
  194. liquid/lex.py +0 -260
  195. liquid/limits.py +0 -66
  196. liquid/loader.py +0 -141
  197. liquid/messages.py +0 -357
  198. liquid/mode.py +0 -12
  199. liquid/output.py +0 -35
  200. liquid/parser.py +0 -119
  201. liquid/span.py +0 -35
  202. liquid/static_analysis.py +0 -443
  203. liquid/stream.py +0 -148
  204. liquid/stringify.py +0 -31
  205. liquid/tag.py +0 -47
  206. liquid/template.py +0 -658
  207. liquid/token.py +0 -145
  208. liquid/undefined.py +0 -218
  209. liquid/utils/__init__.py +0 -15
  210. liquid/utils/html.py +0 -57
  211. liquid/utils/text.py +0 -28
  212. python_liquid-2.3.6.dist-info/RECORD +0 -96
liquid/environment.py CHANGED
@@ -1,611 +1,777 @@
1
- """Shared configuration from which templates can be loaded and parsed."""
2
-
1
+ # pyright: reportUnknownArgumentType=false
2
+ # pyright: reportUnknownVariableType=false
3
+ # pyright: reportReturnType=false
3
4
  from __future__ import annotations
4
5
 
5
- import warnings
6
- from functools import lru_cache
7
- from typing import TYPE_CHECKING
8
- from typing import Any
9
- from typing import Callable
10
- from typing import ClassVar
11
- from typing import Iterator
12
- from typing import Mapping
13
- from typing import Optional
14
- from typing import Type
15
- from typing import Union
16
-
17
- from . import builtin
18
- from .analyze_tags import InnerTagMap
19
- from .analyze_tags import TagAnalysis
20
- from .builtin import DictLoader
21
- from .exceptions import BlockNestingError
22
- from .exceptions import LiquidError
23
- from .exceptions import LiquidSyntaxError
24
- from .exceptions import TemplateInheritanceError
25
- from .exceptions import lookup_warning
26
- from .extra import add_tags_and_filters as register_extra_tags_and_filters
27
- from .lex import get_lexer
28
- from .mode import Mode
29
- from .parser import get_parser
30
- from .stream import TokenStream
31
- from .template import BoundTemplate
32
- from .undefined import Undefined
6
+ import datetime as dt
7
+ import json
8
+ import math
9
+ from collections.abc import (
10
+ Awaitable,
11
+ Callable,
12
+ Collection,
13
+ Container,
14
+ Generator,
15
+ Mapping,
16
+ Sequence,
17
+ )
18
+ from decimal import Decimal
19
+ from typing import TYPE_CHECKING, Any, ClassVar
20
+
21
+ import dateutil
22
+ import markupsafe
23
+
24
+ from . import filters, tags
25
+ from ._chain_map import ReadOnlyChainMap
26
+ from ._drop import liquid_primitive
27
+ from ._io import StringBuffer
28
+ from ._lexer_legacy import LegacyLexer
29
+ from ._nothing import Nothing
30
+ from ._parser_legacy import LegacyParser
31
+ from ._resource_limits import ResourceLimits
32
+ from ._template import Template
33
+ from .drops import Undefined
34
+ from .exceptions import LiquidTypeError
35
+ from .loaders import DictLoader
33
36
 
34
37
  if TYPE_CHECKING:
35
- from pathlib import Path
36
-
37
- from .ast import Node
38
- from .context import RenderContext
39
- from .loader import BaseLoader
40
- from .tag import Tag
41
- from .token import Token
38
+ from ._context import RenderContext
39
+ from ._filter import Filter
40
+ from ._lexer import Lexer
41
+ from ._loader import Loader
42
+ from ._markup import Tag
43
+ from ._parser import Parser
44
+ from .tokens import Token
42
45
 
43
46
 
44
47
  class Environment:
45
- """Shared configuration from which templates can be loaded and parsed.
46
-
47
- An `Environment` is where you might register custom tags and filters, or store
48
- global context variables that should be included with every template.
49
-
50
- Args:
51
- extra: If `True`, register all extra tags and filters. Defaults to `False`.
52
- tag_start_string: The sequence of characters indicating the start of a
53
- liquid tag.
54
- tag_end_string: The sequence of characters indicating the end of a liquid
55
- tag.
56
- statement_start_string: The sequence of characters indicating the start of
57
- an output statement.
58
- statement_end_string: The sequence of characters indicating the end of an
59
- output statement.
60
- template_comments: If `True`, enable template comments, where, by default,
61
- anything between `{#` and `#}` is considered a comment.
62
- comment_start_string: The sequence of characters indicating the start of a
63
- comment. `template_comments` must be `True` for `comment_start_string`
64
- to have any effect.
65
- comment_end_string: The sequence of characters indicating the end of a
66
- comment. `template_comments` must be `True` for `comment_end_string`
67
- to have any effect.
68
- tolerance: Indicates how tolerant to be of errors. Must be one of
69
- `Mode.LAX`, `Mode.WARN` or `Mode.STRICT`.
70
- loader: A template loader. If you want to use the builtin "render" or
71
- "include" tags, a loader must be configured.
72
- undefined: A subclass of `Undefined` that represents undefined values. Could be
73
- one of the built-in undefined types, `Undefined`, `DebugUndefined` or
74
- `StrictUndefined`.
75
- strict_filters: If `True`, will raise an exception upon finding an
76
- undefined filter. Otherwise undefined filters are silently ignored.
77
- autoescape: If `True`, all render context values will be HTML-escaped before
78
- output unless they've been explicitly marked as "safe".
79
- globals: An optional mapping that will be added to the render context of any
80
- template loaded from this environment.
81
- """
82
-
83
- block_nesting_limit: ClassVar[int] = 30
84
- """The maximum markup block nesting depth allowed before a `BlockNestingError`
85
- exception is raised."""
86
-
87
- context_depth_limit: ClassVar[int] = 30
88
- """The maximum number of times a render context can be extended or wrapped before
89
- raising a `ContextDepthError`."""
90
-
91
- loop_iteration_limit: ClassVar[Optional[int]] = None
92
- """The maximum number of loop iterations allowed before a LoopIterationLimitError is
93
- raised."""
94
-
95
- local_namespace_limit: ClassVar[Optional[int]] = None
96
- """The maximum number of bytes (according to `sys.getsizeof`) allowed in a
97
- template's local namespace before a LocalNamespaceLimitError is raised. We only
98
- count the size of the namespaces values, not the size of keys/names."""
99
-
100
- output_stream_limit: ClassVar[Optional[int]] = None
101
- """The maximum number of bytes that can be written to a template's output stream
102
- before raising an OutputStreamLimitError."""
103
-
104
- template_class: Type[BoundTemplate] = BoundTemplate
105
- """Instances of `template_class` are returned from `from_string`, `get_template`
106
- and `get_template_async`. It should be the `BoundTemplate` class or a subclass of
107
- it."""
108
-
109
- suppress_blank_control_flow_blocks: bool = True
110
- """When `True`, don't render control flow blocks that contain only whitespace."""
111
-
112
- shorthand_indexes: bool = False
113
- """When `True`, accept indexes without enclosing square brackets in paths to
114
- variables. Defaults to `False`."""
115
-
116
- string_sequences: bool = False
117
- """When `True`, strings are treated as sequences. That is, characters (Unicode code
118
- points) in a string can be looped over and selected by index. Defaults to `False`.
48
+ """Liquid template parsing and rendering configuration.
49
+
50
+ Parameters
51
+ ----------
52
+ autoescape
53
+ When ``True``, apply HTML-escaping to variables before writing them to the output
54
+ buffer.
55
+ bare_brackets
56
+ When ``True``, allow variables to start with a bracketed segment `[var]`.
57
+ conventional_operator_precedence
58
+ When ``True``, give logical ``and`` and ``or`` operators conventional precedence
59
+ (``and`` binds tighter than ``or``) instead of legacy Liquid's right-associative
60
+ behavior.
61
+ extra
62
+ Enable all built-in, non-standard tags and filters.
63
+ globals
64
+ A mapping of variables that will be attached to the Liquid environment. These
65
+ variables will be available to all templates rendered from the environment.
66
+ iterable_strings
67
+ When ``True``, allow strings to be iterated with the ``{% for %}`` tag.
68
+ loader
69
+ A template loader used by `get_template`, the `{% render %}` tag and any other
70
+ tags that need to load templates.
71
+ parser
72
+ The parser to use. Built-in parsers are :class:`liquid.LegacyParser`,
73
+ :class:`liquid.ExtendedParser`, :class:`liquid.LaxLegacyParser` and
74
+ :class:`liquid.LaxExtendedParser`.
75
+ resource_limits
76
+ Limits used during template parsing an rendering to prevent malicious template
77
+ authors from consuming to much memory or too many CPU cycles.
78
+ shorthand_indexes
79
+ When ``True``, allow dotted indexes in variable paths. ``a.1`` as well as
80
+ ``a[1]``.
81
+ strict_filters
82
+ When ``True``, raise an exception if a filter is unknown or is given unacceptable
83
+ arguments. Otherwise silently ignore the filter invocation.
84
+ tokenizer
85
+ The tokenizer to use. Built-in tokenizers are :class:`liquid.LegacyLexer` and
86
+ :class:`liquid.ExtendedLexer`.
87
+ undefined
88
+ The class used to represent undefined template variables. Could be one of
89
+ :class:`liquid.Undefined`, :class:`liquid.StrictUndefined` or
90
+ :class:`liquid.FalsyUndefined`.
91
+
92
+ Attributes
93
+ ----------
94
+ tags : dict[str, Tag]
95
+ A mapping of tag names to tag implementations. It's OK to update this dictionary
96
+ after instantiating an environment, or override `setup_tags_and_filters`.
97
+ filters : dict[str, Filter]
98
+ A mapping of filter names to filter implementations. It's OK to update this
99
+ dictionary after instantiating an environment, or override
100
+ `setup_tags_and_filters`.
119
101
  """
120
102
 
121
- string_first_and_last: bool = False
122
- """When `True`, the special `first` and `last` properties will return the first and
123
- last charters of a string. Otherwise `first` and `last` will resolve to Undefined
124
- when applied to a string. Defaults to `False`."""
125
-
126
- logical_not_operator: bool = False
127
- """When `True`, allow the use of the logical `not` operator in logical expressions.
128
- Defaults to `False`.
129
- """
130
-
131
- logical_parentheses: bool = False
132
- """When `True`, allow the use of parentheses in logical expressions to group terms.
133
- Defaults to `False.`"""
134
-
135
- ternary_expressions: bool = False
136
- """When `True`, allow the use of ternary expression in output statements, assign
137
- tags and echo tags. Defaults to `False`."""
138
-
139
- keyword_assignment: bool = False
140
- """When `True` accept `=` or `:` as the separator token between argument names
141
- and argument values. By default only `:` is allowed."""
103
+ standard_tags: ClassVar[dict[str, Tag]] = {
104
+ "assign": tags.AssignTag,
105
+ "break": tags.BreakTag,
106
+ "capture": tags.CaptureTag,
107
+ "case": tags.CaseTag,
108
+ "comment": tags.CommentTag,
109
+ "continue": tags.ContinueTag,
110
+ "cycle": tags.CycleTag,
111
+ "decrement": tags.DecrementTag,
112
+ "doc": tags.DocTag,
113
+ "echo": tags.EchoTag,
114
+ "for": tags.ForTag,
115
+ "if": tags.IfTag,
116
+ "ifchanged": tags.IfChangedTag,
117
+ "include": tags.IncludeTag,
118
+ "increment": tags.IncrementTag,
119
+ "liquid": tags.LiquidTag,
120
+ "raw": tags.RawTag,
121
+ "render": tags.RenderTag,
122
+ "tablerow": tags.TableRowTag,
123
+ "unless": tags.UnlessTag,
124
+ "#": tags.InlineCommentTag,
125
+ }
126
+
127
+ extra_tags: ClassVar[dict[str, Tag]] = {
128
+ "block": tags.BlockTag,
129
+ "call": tags.CallTag,
130
+ "extends": tags.ExtendsTag,
131
+ "macro": tags.MacroTag,
132
+ "translate": tags.TranslateTag,
133
+ "with": tags.WithTag,
134
+ }
135
+
136
+ standard_filters: ClassVar[dict[str, Filter]] = {
137
+ "abs": filters.abs_,
138
+ "append": filters.append,
139
+ "at_least": filters.at_least,
140
+ "at_most": filters.at_most,
141
+ "base64_decode": filters.base64_decode,
142
+ "base64_encode": filters.base64_encode,
143
+ "base64_url_safe_decode": filters.base64_url_safe_decode,
144
+ "base64_url_safe_encode": filters.base64_url_safe_encode,
145
+ "ceil": filters.ceil,
146
+ "capitalize": filters.capitalize,
147
+ "compact": filters.compact,
148
+ "concat": filters.concat,
149
+ "date": filters.date,
150
+ "default": filters.default,
151
+ "divided_by": filters.divided_by,
152
+ "downcase": filters.downcase,
153
+ "escape_once": filters.escape_once,
154
+ "escape": filters.escape,
155
+ "h": filters.escape,
156
+ "escapejs": filters.escapejs,
157
+ "find": filters.find,
158
+ "find_index": filters.find_index,
159
+ "first": filters.first,
160
+ "floor": filters.floor,
161
+ "has": filters.has,
162
+ "join": filters.join,
163
+ "last": filters.last,
164
+ "lstrip": filters.lstrip,
165
+ "map": filters.map_,
166
+ "minus": filters.minus,
167
+ "modulo": filters.modulo,
168
+ "newline_to_br": filters.newline_to_br,
169
+ "plus": filters.plus,
170
+ "prepend": filters.prepend,
171
+ "reject": filters.reject,
172
+ "remove": filters.remove,
173
+ "remove_first": filters.remove_first,
174
+ "remove_last": filters.remove_last,
175
+ "replace": filters.replace,
176
+ "replace_first": filters.replace_first,
177
+ "replace_last": filters.replace_last,
178
+ "reverse": filters.reverse,
179
+ "round": filters.round_,
180
+ "rstrip": filters.rstrip,
181
+ "safe": filters.safe,
182
+ "size": filters.size,
183
+ "slice": filters.slice_,
184
+ "sort": filters.sort,
185
+ "sort_natural": filters.sort_natural,
186
+ "split": filters.split,
187
+ "squish": filters.squish,
188
+ "strip": filters.strip,
189
+ "strip_html": filters.strip_html,
190
+ "strip_newlines": filters.strip_newlines,
191
+ "sum": filters.sum_,
192
+ "times": filters.times,
193
+ "truncate": filters.truncate,
194
+ "truncatewords": filters.truncate_words,
195
+ "uniq": filters.uniq,
196
+ "upcase": filters.upcase,
197
+ "url_decode": filters.url_decode,
198
+ "url_encode": filters.url_encode,
199
+ "where": filters.where,
200
+ }
201
+
202
+ extra_filters: ClassVar[dict[str, Filter]] = {
203
+ "currency": filters.Currency(),
204
+ "datetime": filters.DateTime(),
205
+ "decimal": filters.Number(),
206
+ "gettext": filters.GetText(),
207
+ "index": filters.index,
208
+ "json": filters.JSON(),
209
+ "money_with_currency": filters.Currency(default_format="¤#,##0.00 ¤¤"),
210
+ "money_without_currency": filters.Currency(default_format="#,##0.00"),
211
+ "money_without_trailing_zeros": filters.Currency(
212
+ default_format="¤#,###", currency_digits=False
213
+ ),
214
+ "money": filters.Currency(),
215
+ "ngettext": filters.NGetText(),
216
+ "npgettext": filters.NPGetText(),
217
+ "pgettext": filters.PGetText(),
218
+ "sort_numeric": filters.sort_numeric,
219
+ "script_tag": filters.script_tag,
220
+ "stylesheet_tag": filters.stylesheet_tag,
221
+ "t": filters.Translate(),
222
+ "unit": filters.Unit(),
223
+ }
142
224
 
143
225
  def __init__(
144
226
  self,
145
227
  *,
228
+ autoescape: bool = False,
229
+ bare_brackets: bool = True,
230
+ conventional_operator_precedence: bool = False,
146
231
  extra: bool = False,
147
- tag_start_string: str = r"{%",
148
- tag_end_string: str = r"%}",
149
- statement_start_string: str = r"{{",
150
- statement_end_string: str = r"}}",
151
- tolerance: Mode = Mode.STRICT,
152
- loader: Optional[BaseLoader] = None,
153
- undefined: Type[Undefined] = Undefined,
232
+ globals: Mapping[str, object] | None = None,
233
+ iterable_strings: bool = False,
234
+ loader: Loader | None = None,
235
+ parser: type[Parser] = LegacyParser,
236
+ resource_limits: ResourceLimits | None = None,
237
+ shorthand_indexes: bool = False,
154
238
  strict_filters: bool = True,
155
- autoescape: bool = False,
156
- globals: Optional[Mapping[str, object]] = None, # noqa: A002
157
- template_comments: bool = False,
158
- comment_start_string: str = "{#",
159
- comment_end_string: str = "#}",
160
- ):
161
- self.tag_start_string = tag_start_string
162
- self.tag_end_string = tag_end_string
163
- self.statement_start_string = statement_start_string
164
- self.statement_end_string = statement_end_string
165
-
166
- # An instance of a template loader implementing `liquid.loaders.BaseLoader`.
167
- # `get_template()` will delegate to this loader.
239
+ tokenizer: type[Lexer] = LegacyLexer,
240
+ undefined: type[Undefined] = Undefined,
241
+ ) -> None:
168
242
  self.loader = loader or DictLoader({})
243
+ self.globals = globals
244
+ self.undefined_type = undefined
169
245
 
170
- # A mapping of template variable names to python objects. These variables will
171
- # be added to the global namespace of any template rendered from this
172
- # environment using `from_string` or `get_template`.
173
- self.globals: Mapping[str, object] = globals or {}
246
+ self.allow_bare_brackets = bare_brackets
247
+ self.strict_filters = strict_filters
248
+ self.autoescape = autoescape
249
+ self.iterable_strings = iterable_strings
250
+ self.shorthand_indexes = shorthand_indexes
251
+ self.conventional_operator_precedence = conventional_operator_precedence
174
252
 
175
- # Extended template comment syntax control.
176
- self.template_comments = template_comments
177
- self.comment_start_string = comment_start_string
178
- self.comment_end_string = comment_end_string
179
- if not self.template_comments:
180
- self.comment_start_string = ""
181
- self.comment_end_string = ""
253
+ self.tokenizer = tokenizer
254
+ self.parser = parser
182
255
 
183
- self.undefined: Type[Undefined] = undefined
184
- self.strict_filters: bool = strict_filters
185
- self.autoescape: bool = autoescape
186
- self.mode: Mode = tolerance
256
+ self.resource_limits = resource_limits or ResourceLimits()
187
257
 
188
258
  self.tags: dict[str, Tag] = {}
189
- """The environment's tag register, mapping tag names to instances of `Tag`."""
190
-
191
- self.filters: dict[str, Callable[..., Any]] = {}
192
- """The environment's filter register, mapping filter names to callables."""
193
-
194
- self.setup_tags_and_filters(extra=extra)
195
-
196
- def __hash__(self) -> int:
197
- return hash(
198
- (
199
- self.statement_start_string,
200
- self.statement_end_string,
201
- self.tag_start_string,
202
- self.tag_end_string,
203
- self.comment_start_string,
204
- self.comment_end_string,
205
- self.mode,
206
- )
207
- )
208
-
209
- def tokenizer(self) -> Callable[[str], Iterator[Token]]:
210
- """Return a tokenizer for this environment."""
211
- return get_lexer(
212
- self.tag_start_string,
213
- self.tag_end_string,
214
- self.statement_start_string,
215
- self.statement_end_string,
216
- self.comment_start_string,
217
- self.comment_end_string,
218
- )
259
+ self.filters: dict[str, Filter] = {}
219
260
 
220
- def add_tag(self, tag: Type[Tag]) -> None:
221
- """Register a liquid tag with the environment.
261
+ self.buffer_factory: Callable[[], StringBuffer] = StringBuffer
222
262
 
223
- Built-in tags are registered for you automatically with every new `Environment`.
263
+ self.persistent_registers: Collection[str] = ("extends",)
224
264
 
225
- Args:
226
- tag: The tag to register.
227
- """
228
- self.tags[tag.name] = tag(self)
229
-
230
- def add_filter(self, name: str, func: Callable[..., Any]) -> None:
231
- """Register a filter function with the environment.
232
-
233
- Args:
234
- name: The filter's name. Does not need to match the function name. This is
235
- what you'll use to apply the filter to an expression in a liquid
236
- template.
237
- func: Any callable that accepts at least one argument, the result of the
238
- expression the filter is applied to. If the filter needs access to the
239
- active environment or render context, use `liquid.filer.with_context`
240
- and/or `liquid.filter.with_environment` decorators.
241
- """
242
- self.filters[name] = func
265
+ self.setup_tags_and_filters(extra=extra)
243
266
 
244
267
  def setup_tags_and_filters(self, *, extra: bool = False) -> None:
245
- """Add default tags and filters to this environment.
268
+ self.tags.update(self.standard_tags)
269
+ self.filters.update(self.standard_filters)
246
270
 
247
- If _extra_ is `True`, register all extra, non-standard tags and filters too.
248
- """
249
- builtin.register(self)
250
271
  if extra:
251
- register_extra_tags_and_filters(self)
272
+ self.tags.update(self.extra_tags)
273
+ self.filters.update(self.extra_filters)
252
274
 
253
- def _parse(self, source: str) -> list[Node]:
254
- """Parse _source_ as a Liquid template.
275
+ def get_template(
276
+ self,
277
+ name: str,
278
+ *,
279
+ globals: Mapping[str, object] | None = None,
280
+ context: RenderContext | None = None,
281
+ **kwargs: object,
282
+ ) -> Template:
283
+ """Load and parse the template identified by `name` using the configured loader.
284
+
285
+ Parameters
286
+ ----------
287
+ name
288
+ The template's name or identifier. The template loader is responsible for
289
+ interpreting `name`. It could be the name of a file on the file system or
290
+ the value in a field in a database.
291
+ globals
292
+ A mapping of variables that will be attached to the resulting template.
293
+ context
294
+ The current render context, if one is available.
295
+ kwargs
296
+ Arbitrary arguments passed to the template loader that can be used to narrow
297
+ the template search space.
298
+
299
+ Raises
300
+ ------
301
+ LiquidSyntaxError
302
+ If the template source text contains invalid Liquid markup.
303
+ TemplateNotFoundError
304
+ If `name` is not known to the configured template loader.
305
+ """
306
+ return self.loader.load(self, name, globals, context, **kwargs)
255
307
 
256
- More often than not you'll want to use `Environment.from_string` instead.
308
+ async def get_template_async(
309
+ self,
310
+ name: str,
311
+ *,
312
+ globals: Mapping[str, object] | None = None,
313
+ context: RenderContext | None = None,
314
+ **kwargs: object,
315
+ ) -> Template:
316
+ """Load and parse the template identified by `name` using the configured loader.
317
+
318
+ Parameters
319
+ ----------
320
+ name
321
+ The template's name or identifier. The template loader is responsible for
322
+ interpreting `name`. It could be the name of a file on the file system or
323
+ the value in a field in a database.
324
+ globals
325
+ A mapping of variables that will be attached to the resulting template.
326
+ context
327
+ The current render context, if one is available.
328
+ kwargs
329
+ Arbitrary arguments passed to the template loader that can be used to narrow
330
+ the template search space.
331
+
332
+ Raises
333
+ ------
334
+ LiquidSyntaxError
335
+ If the template source text contains invalid Liquid markup.
336
+ TemplateNotFoundError
337
+ If `name` is not known to the configured template loader.
257
338
  """
258
- parser = get_parser(self)
259
- token_iter = self.tokenizer()(source)
260
- return parser.parse(TokenStream(token_iter))
339
+ return await self.loader.load_async(self, name, globals, context, **kwargs)
261
340
 
262
- def from_string(
341
+ def parse(
263
342
  self,
264
343
  source: str,
344
+ *,
265
345
  name: str = "",
266
- path: Optional[Union[str, Path]] = None,
267
- globals: Optional[Mapping[str, object]] = None, # noqa: A002
268
- matter: Optional[Mapping[str, object]] = None,
269
- ) -> BoundTemplate:
270
- """Parse the given string as a liquid template.
271
-
272
- Args:
273
- source: The liquid template source code.
274
- name: Optional name of the template. Available as `Template.name`.
275
- path: Optional path or identifier to the origin of the template.
276
- globals: An optional mapping of render context variables attached
277
- to the resulting template.
278
- matter: Optional mapping of render context variables associated
279
- with the template. Could be "front matter" or other meta data.
346
+ path: str | None = None,
347
+ globals: Mapping[str, object] | None = None,
348
+ matter: Mapping[str, object] | None = None,
349
+ up_to_date: Callable[[], bool | Awaitable[bool]] | None = None,
350
+ ) -> Template:
351
+ """Parse `source` as a Liquid template.
352
+
353
+ Parameters
354
+ ----------
355
+ source
356
+ Liquid template source code.
357
+ name
358
+ An optional name for the template. This name will appear in exception
359
+ messages.
360
+ path
361
+ An optional path to `name`, if `source` represents a file or other resource
362
+ with a path.
363
+ globals
364
+ A mapping of variables that will be attached to the resulting template.
365
+ matter
366
+ A mapping of variables associated with `source`. This could be front matter
367
+ or meta data read from a database, for example.
368
+ up_to_date
369
+ A function use by the resulting template to determine if it needs to be
370
+ loaded again after consulting a template cache.
280
371
  """
281
- try:
282
- nodes = self._parse(source)
283
- except (LiquidSyntaxError, TemplateInheritanceError, BlockNestingError) as err:
284
- err.template_name = path
285
- raise err
286
- except Exception as err: # noqa: BLE001
287
- raise LiquidError("unexpected liquid parsing error", token=None) from err
288
- return self.template_class(
289
- env=self,
290
- name=name,
372
+ return Template(
373
+ self,
374
+ source,
375
+ name,
376
+ self.parser.parse(self, source, name),
291
377
  path=path,
292
- nodes=nodes,
293
378
  globals=self.make_globals(globals),
294
379
  matter=matter,
380
+ up_to_date=up_to_date,
295
381
  )
296
382
 
297
- def parse(
298
- self,
299
- source: str,
300
- name: str = "",
301
- path: Optional[Union[str, Path]] = None,
302
- globals: Optional[Mapping[str, object]] = None, # noqa: A002
303
- matter: Optional[Mapping[str, object]] = None,
304
- ) -> BoundTemplate:
305
- """Parse the given string as a liquid template.
306
-
307
- Args:
308
- source: The liquid template source code.
309
- name: Optional name of the template. Available as `Template.name`.
310
- path: Optional path or identifier to the origin of the template.
311
- globals: An optional mapping of render context variables attached
312
- to the resulting template.
313
- matter: Optional mapping of render context variables associated
314
- with the template. Could be "front matter" or other meta data.
383
+ def render(self, source: str, data: Mapping[str, object] | None = None) -> str:
384
+ """Parse and render `source` with variables from `data`
385
+
386
+ Parameters
387
+ ----------
388
+ source
389
+ Template source code.
390
+ data
391
+ Template variables.
315
392
  """
316
- return self.from_string(
317
- source, name=name, path=path, globals=globals, matter=matter
318
- )
393
+ return self.parse(source).render(data)
394
+
395
+ async def render_async(
396
+ self, source: str, data: Mapping[str, object] | None = None
397
+ ) -> str:
398
+ """Parse and render `source` asynchronously with variables from `data`.
399
+
400
+ Parameters
401
+ ----------
402
+ source
403
+ Template source code.
404
+ data
405
+ Template variables.
406
+ """
407
+ return await self.parse(source).render_async(data)
319
408
 
320
- def render(self, source: str, **data: object) -> str:
321
- """Parse and render source text."""
322
- return self.parse(source).render(**data)
409
+ def tokenize(self, source: str) -> list[Token]:
410
+ return self.tokenizer.tokenize(self, source)
323
411
 
324
- async def render_async(self, source: str, **data: object) -> str:
325
- """Parse and render source text."""
326
- return await self.parse(source).render_async(**data)
412
+ def make_globals(
413
+ self, data: Mapping[str, object] | None
414
+ ) -> Mapping[str, object] | None:
415
+ if data is None:
416
+ return self.globals
417
+
418
+ if self.globals is None:
419
+ return data
420
+
421
+ return ReadOnlyChainMap(data, self.globals)
422
+
423
+ def serialize(self, obj: object, context: RenderContext, span: Token) -> str:
424
+ """Stringify `obj` suitable for output."""
425
+ if liquid_primitive(obj):
426
+ obj = obj.__liquid__("output", context)
427
+
428
+ if isinstance(obj, str):
429
+ result = obj
430
+
431
+ elif isinstance(obj, Sequence):
432
+ result = (markupsafe.Markup("") if self.autoescape else "").join(
433
+ self.to_str(item, context, span) for item in _flatten(obj)
434
+ )
435
+
436
+ else:
437
+ result = self.to_str(obj, context, span)
438
+
439
+ return markupsafe.escape(result) if self.autoescape else result
440
+
441
+ def trim(self, text: str, left: str | None, right: str | None) -> str:
442
+ if left == "-" and right == "-":
443
+ return text.strip()
444
+
445
+ if left == "-":
446
+ return text.lstrip()
447
+
448
+ if right == "-":
449
+ return text.rstrip()
450
+
451
+ return text
452
+
453
+ def truthy(self, obj: object, context: RenderContext) -> bool:
454
+ if liquid_primitive(obj):
455
+ return bool(obj.__liquid__("boolean", context))
456
+
457
+ return not (obj is False or obj is None)
458
+
459
+ def eq(
460
+ self, left: object, right: object, context: RenderContext, span: Token
461
+ ) -> bool:
462
+ if liquid_primitive(right):
463
+ right = right.__liquid__("object", context)
464
+
465
+ if type(left) is bool and type(right) is int:
466
+ return False
467
+
468
+ if type(right) is bool and type(left) is int:
469
+ return False
470
+
471
+ return left == right
472
+
473
+ def lt(
474
+ self, left: object, right: object, context: RenderContext, span: Token
475
+ ) -> bool:
476
+ if isinstance(left, str):
477
+ if isinstance(right, str):
478
+ return left < right
479
+ return left < self.to_str(right, context, span)
480
+
481
+ if type(left) is bool or type(right) is bool:
482
+ return False
483
+
484
+ if isinstance(left, (int, float, Decimal)):
485
+ if isinstance(right, (int, float, Decimal)):
486
+ return left < right
487
+ if liquid_primitive(right):
488
+ return left < self.to_numeric(right, context, 0)
489
+
490
+ if self.is_nil(left) or self.is_nil(right):
491
+ return False
327
492
 
328
- def get_template(
329
- self,
330
- name: str,
331
- *,
332
- globals: Mapping[str, object] | None = None, # noqa: A002
333
- context: RenderContext | None = None,
334
- **kwargs: object,
335
- ) -> BoundTemplate:
336
- """Load and parse a template using the configured loader.
337
-
338
- Args:
339
- name: The template's name. The loader is responsible for interpreting
340
- the name. It could be the name of a file or some other identifier.
341
- globals: A mapping of render context variables attached to the
342
- resulting template.
343
- context: An optional render context that can be used to narrow the template
344
- source search space.
345
- kwargs: Arbitrary arguments that can be used to narrow the template source
346
- search space.
347
-
348
- Raises:
349
- TemplateNotFound: If a template with the given name can not be found.
350
- """
351
493
  try:
352
- return self.loader.load(
353
- env=self,
354
- name=name,
355
- globals=self.make_globals(globals),
356
- context=context,
357
- **kwargs,
494
+ return left < right # type: ignore
495
+ except TypeError:
496
+ raise LiquidTypeError(
497
+ f"{left.__class__.__name__} and {right.__class__.__name__} are not comparable",
498
+ token=span,
499
+ source=context.template.source,
500
+ name=context.template.name,
358
501
  )
359
- except LiquidError as err:
360
- if not err.template_name:
361
- err.template_name = name
362
- raise
363
502
 
364
- async def get_template_async(
365
- self,
366
- name: str,
367
- *,
368
- globals: Mapping[str, object] | None = None, # noqa: A002
369
- context: RenderContext | None = None,
370
- **kwargs: object,
371
- ) -> BoundTemplate:
372
- """An async version of `get_template()`."""
503
+ def le(
504
+ self, left: object, right: object, context: RenderContext, span: Token
505
+ ) -> bool:
506
+ if isinstance(left, str):
507
+ if isinstance(right, str):
508
+ return left <= right
509
+ if liquid_primitive(right):
510
+ return left <= self.to_str(right, context, span)
511
+
512
+ if type(left) is bool or type(right) is bool:
513
+ return False
514
+
515
+ if isinstance(left, (int, float, Decimal)):
516
+ if isinstance(right, (int, float, Decimal)):
517
+ return left <= right
518
+ if liquid_primitive(right):
519
+ return left <= self.to_numeric(right, context, 0)
520
+
521
+ if self.is_nil(left) or self.is_nil(right):
522
+ return False
523
+
373
524
  try:
374
- return await self.loader.load_async(
375
- env=self,
376
- name=name,
377
- globals=self.make_globals(globals),
378
- context=context,
379
- **kwargs,
525
+ result = left < right # type: ignore
526
+ except TypeError:
527
+ raise LiquidTypeError(
528
+ f"{left.__class__.__name__} and {right.__class__.__name__} are not comparable",
529
+ token=span,
530
+ source=context.template.source,
531
+ name=context.template.name,
380
532
  )
381
- except LiquidError as err:
382
- if not err.template_name:
383
- err.template_name = name
384
- raise
385
533
 
386
- def analyze_tags_from_string(
387
- self,
388
- source: str,
389
- name: str = "<string>",
390
- *,
391
- inner_tags: Optional[InnerTagMap] = None,
392
- ) -> TagAnalysis:
393
- """Analyze tags in template source text.
394
-
395
- Unlike template static or contextual analysis, a tag audit does not parse the
396
- template source text into an AST, nor does it attempt to load partial templates
397
- from `{% include %}` or `{% render %}` tags.
398
-
399
- Args:
400
- source: The source text of the template.
401
- name: A name or identifier for the template.
402
- inner_tags: A mapping of block tags to a list of allowed "inner" tags for
403
- the block. For example, `{% if %}` blocks are allowed to contain
404
- `{% elsif %}` and `{% else %}` tags.
405
- """
406
- return TagAnalysis(
407
- env=self,
408
- name=name,
409
- tokens=list(self.tokenizer()(source)),
410
- inner_tags=inner_tags,
534
+ return result or self.eq(left, right, context, span)
535
+
536
+ def contains(
537
+ self, left: object, right: object, context: RenderContext, span: Token
538
+ ) -> bool:
539
+ if not (self.truthy(left, context) and self.truthy(right, context)):
540
+ return False
541
+
542
+ if isinstance(left, str):
543
+ return left.find(self.to_str(right, context, span)) != -1
544
+
545
+ if isinstance(left, Sequence):
546
+ try:
547
+ return left.index(right) != -1 and self.truthy(right, context)
548
+ except ValueError:
549
+ return False
550
+
551
+ if isinstance(left, Container):
552
+ try:
553
+ return right in left
554
+ except TypeError:
555
+ return False
556
+
557
+ raise LiquidTypeError(
558
+ f"{left.__class__.__name__} is not a container",
559
+ token=span,
560
+ source=context.template.source,
561
+ name=context.template.name,
411
562
  )
412
563
 
413
- def analyze_tags(
414
- self,
415
- name: str,
416
- *,
417
- context: Optional["RenderContext"] = None,
418
- inner_tags: Optional[InnerTagMap] = None,
419
- **kwargs: str,
420
- ) -> TagAnalysis:
421
- """Audit template tags without parsing source text into an abstract syntax tree.
422
-
423
- This is useful for identifying unknown, misplaced and unbalanced tags in a
424
- template's source text. See also `liquid.template.BoundTemplate.analyze`.
425
-
426
- Args:
427
- name: The template's name or identifier, as you would use with
428
- `Environment.get_template`. Use `Environment.analyze_tags_from_string`
429
- to audit tags in template text without using a template loader.
430
- context: An optional render context the loader might use to modify the
431
- template search space. If given, uses
432
- `liquid.loaders.BaseLoader.get_source_with_context` from the current
433
- loader.
434
- inner_tags: A mapping of block tags to a list of allowed "inner" tags for
435
- the block. For example, `{% if %}` blocks are allowed to contain
436
- `{% elsif %}` and `{% else %}` tags.
437
- kwargs: Loader context.
564
+ def undefined(
565
+ self, name: str, span: Token, source: str, template_name: str
566
+ ) -> object:
567
+ return self.undefined_type(name, span, source, template_name)
568
+
569
+ def to_int(self, obj: object, context: RenderContext, span: Token) -> int:
570
+ if isinstance(obj, int | float | Decimal):
571
+ return math.trunc(obj)
572
+
573
+ if self.is_nil(obj):
574
+ return 0
575
+
576
+ try:
577
+ return math.trunc(float(str(obj)))
578
+ except (TypeError, ValueError):
579
+ raise LiquidTypeError(
580
+ "invalid integer",
581
+ token=span,
582
+ source=context.template.source,
583
+ name=context.template.name,
584
+ )
585
+
586
+ def to_numeric(
587
+ self, obj: object, context: RenderContext, default: int | Decimal = 0
588
+ ) -> float | int | Decimal:
589
+ if liquid_primitive(obj):
590
+ obj = obj.__liquid__("numeric", context)
591
+
592
+ if type(obj) is bool:
593
+ return default
594
+
595
+ if isinstance(obj, int | float | Decimal):
596
+ return obj
597
+
598
+ if isinstance(obj, str):
599
+ try:
600
+ return int(obj)
601
+ except ValueError:
602
+ pass
603
+
604
+ try:
605
+ return float(obj)
606
+ except ValueError:
607
+ return default
608
+
609
+ return default
610
+
611
+ def to_str(self, obj: object, context: RenderContext, span: Token) -> str:
612
+ if liquid_primitive(obj):
613
+ obj = obj.__liquid__("string", context)
614
+
615
+ if obj is None:
616
+ return ""
617
+
618
+ if isinstance(obj, str):
619
+ return obj
620
+
621
+ if isinstance(obj, Mapping | Sequence):
622
+ return self._inspect(obj, context)
623
+
624
+ if type(obj) is bool:
625
+ return str(obj).lower()
626
+
627
+ return str(obj)
628
+
629
+ def to_array(
630
+ self, obj: object, context: RenderContext, span: Token
631
+ ) -> list[object]:
632
+ if liquid_primitive(obj):
633
+ obj = obj.__liquid__("array", context)
634
+
635
+ if isinstance(obj, list):
636
+ return obj
637
+
638
+ if isinstance(obj, str) and not self.iterable_strings:
639
+ return [] if not obj else [obj]
640
+
641
+ if isinstance(obj, Sequence):
642
+ return list(obj) # pyright: ignore[reportUnknownArgumentType]
643
+
644
+ if isinstance(obj, Mapping):
645
+ return [(k, v) for k, v in obj.items()] # pyright: ignore[reportUnknownVariableType]
646
+
647
+ if self.is_nil(obj) or type(obj) is bool:
648
+ return []
649
+
650
+ return [obj]
651
+
652
+ def to_date(
653
+ self, obj: object, context: RenderContext, span: Token
654
+ ) -> dt.datetime | None:
655
+ """Return `obj` coerced to a datetime, or ``None`` on failure.
656
+
657
+ Parameters
658
+ ----------
659
+ obj
660
+ The object to convert to a datetime.
661
+ context
662
+ The active render context.
663
+ span
664
+ A token suitable for use with error messages.
438
665
  """
439
- template_source = self.loader.get_source(
440
- self, template_name=name, context=context, **kwargs
441
- )
666
+ if isinstance(obj, dt.datetime):
667
+ return obj
442
668
 
443
- return self.analyze_tags_from_string(
444
- template_source.text,
445
- name=template_source.name,
446
- inner_tags=inner_tags,
447
- )
669
+ if isinstance(obj, str):
670
+ if not obj:
671
+ return None
448
672
 
449
- async def analyze_tags_async(
450
- self,
451
- name: str,
452
- *,
453
- context: Optional["RenderContext"] = None,
454
- inner_tags: Optional[InnerTagMap] = None,
455
- **kwargs: str,
456
- ) -> TagAnalysis:
457
- """An async version of `Environment.analyze_tags`."""
458
- template_source = await self.loader.get_source_async(
459
- env=self, template_name=name, context=context, **kwargs
460
- )
673
+ if obj.lower() in ("now", "today"):
674
+ return dt.datetime.now()
461
675
 
462
- return self.analyze_tags_from_string(
463
- template_source.text,
464
- name=template_source.name,
465
- inner_tags=inner_tags,
466
- )
676
+ if obj.isdigit():
677
+ return dt.datetime.fromtimestamp(int(obj))
467
678
 
468
- def make_globals(
469
- self,
470
- globals: Optional[Mapping[str, object]] = None, # noqa: A002
471
- ) -> dict[str, object]:
472
- """Combine environment globals with template globals."""
473
- if globals:
474
- # Template globals take priority over environment globals.
475
- return {**self.globals, **globals}
476
- return dict(self.globals)
477
-
478
- def error(
479
- self,
480
- exc: Union[Type[LiquidError], LiquidError],
481
- msg: Optional[str] = None,
482
- token: Optional[Token] = None,
483
- ) -> None:
484
- """Raise, warn or ignore the given exception according to the current mode."""
485
- if not isinstance(exc, LiquidError):
486
- exc = exc(msg, token=token)
487
- elif not exc.token:
488
- exc.token = token
489
-
490
- if self.mode == Mode.STRICT:
491
- raise exc
492
- if self.mode == Mode.WARN:
493
- warnings.warn(
494
- str(exc), category=lookup_warning(exc.__class__), stacklevel=2
495
- )
679
+ try:
680
+ return dateutil.parser.parse(obj)
681
+ except dateutil.parser.ParserError:
682
+ return None
496
683
 
684
+ if isinstance(obj, int):
685
+ try:
686
+ return dt.datetime.fromtimestamp(obj)
687
+ except (OverflowError, OSError):
688
+ # Testing on Windows shows that it can't handle some
689
+ # negative integers.
690
+ return None
497
691
 
498
- @lru_cache(maxsize=10)
499
- def get_implicit_environment(
500
- *,
501
- extra: bool = False,
502
- tag_start_string: str,
503
- tag_end_string: str,
504
- statement_start_string: str,
505
- statement_end_string: str,
506
- tolerance: Mode,
507
- loader: Optional[BaseLoader],
508
- undefined: Type[Undefined],
509
- strict_filters: bool,
510
- autoescape: bool,
511
- globals: Optional[Mapping[str, object]], # noqa: A002
512
- template_comments: bool,
513
- comment_start_string: str,
514
- comment_end_string: str,
515
- ) -> Environment:
516
- """Return an `Environment` initialized with the given arguments."""
517
- return Environment(
518
- extra=extra,
519
- tag_start_string=tag_start_string,
520
- tag_end_string=tag_end_string,
521
- statement_start_string=statement_start_string,
522
- statement_end_string=statement_end_string,
523
- tolerance=tolerance,
524
- loader=loader,
525
- undefined=undefined,
526
- strict_filters=strict_filters,
527
- autoescape=autoescape,
528
- globals=globals,
529
- template_comments=template_comments,
530
- comment_start_string=comment_start_string,
531
- comment_end_string=comment_end_string,
532
- )
533
-
534
-
535
- # `Template` is a factory function masquerading as a class. The desire to have an
536
- # intuitive API and to please the static type checker outweighs this abuse of Python
537
- # naming conventions. At least for now.
538
-
539
-
540
- def Template( # noqa: N802, D417
541
- source: str,
542
- *,
543
- extra: bool = False,
544
- tag_start_string: str = r"{%",
545
- tag_end_string: str = r"%}",
546
- statement_start_string: str = r"{{",
547
- statement_end_string: str = r"}}",
548
- tolerance: Mode = Mode.STRICT,
549
- undefined: Type[Undefined] = Undefined,
550
- strict_filters: bool = True,
551
- autoescape: bool = False,
552
- globals: Optional[Mapping[str, object]] = None, # noqa: A002
553
- template_comments: bool = False,
554
- comment_start_string: str = "{#",
555
- comment_end_string: str = "#}",
556
- ) -> BoundTemplate:
557
- """Parse a template, automatically creating an `Environment` to bind it to.
558
-
559
- Other than `source`, all arguments are passed to the implicit `Environment`,
560
- which might have been cached from previous calls to `Template`.
561
-
562
- Args:
563
- extra: If `True`, register all extra tags and filters. Defaults to `False`.
564
- tag_start_string: The sequence of characters indicating the start of a
565
- liquid tag.
566
- tag_end_string: The sequence of characters indicating the end of a liquid
567
- tag.
568
- statement_start_string: The sequence of characters indicating the start of
569
- an output statement.
570
- statement_end_string: The sequence of characters indicating the end of an
571
- output statement.
572
- template_comments: If `True`, enable template comments, where, by default,
573
- anything between `{#` and `#}` is considered a comment.
574
- comment_start_string: The sequence of characters indicating the start of a
575
- comment. `template_comments` must be `True` for `comment_start_string`
576
- to have any effect.
577
- comment_end_string: The sequence of characters indicating the end of a
578
- comment. `template_comments` must be `True` for `comment_end_string`
579
- to have any effect.
580
- tolerance: Indicates how tolerant to be of errors. Must be one of
581
- `Mode.LAX`, `Mode.WARN` or `Mode.STRICT`.
582
- undefined: A subclass of `Undefined` that represents undefined values. Could be
583
- one of the built-in undefined types, `Undefined`, `DebugUndefined` or
584
- `StrictUndefined`.
585
- strict_filters: If `True`, will raise an exception upon finding an
586
- undefined filter. Otherwise undefined filters are silently ignored.
587
- autoescape: If `True`, all render context values will be HTML-escaped before
588
- output unless they've been explicitly marked as "safe".
589
- globals: An optional mapping that will be added to the render context of any
590
- template loaded from this environment.
591
- """
592
- # Resorting to named arguments (repeated 3 times) as I've twice missed a bug
593
- # because of positional arguments.
594
- env = get_implicit_environment(
595
- extra=extra,
596
- tag_start_string=tag_start_string,
597
- tag_end_string=tag_end_string,
598
- statement_start_string=statement_start_string,
599
- statement_end_string=statement_end_string,
600
- tolerance=tolerance,
601
- loader=None,
602
- undefined=undefined,
603
- strict_filters=strict_filters,
604
- autoescape=autoescape,
605
- globals=None,
606
- template_comments=template_comments,
607
- comment_start_string=comment_start_string,
608
- comment_end_string=comment_end_string,
609
- )
610
-
611
- return env.from_string(source, globals=globals)
692
+ return None
693
+
694
+ def is_nil(self, obj: object) -> bool:
695
+ return obj is None or isinstance(obj, (Undefined, Nothing))
696
+
697
+ def _inspect(
698
+ self,
699
+ obj: object,
700
+ context: RenderContext,
701
+ circular_placeholder: str = '"[Circular]"',
702
+ ) -> str:
703
+ """Stringify `value` using Ruby `=>` notation."""
704
+ seen: set[int] = set()
705
+
706
+ def stringify(val: Any) -> str | None:
707
+ if val is None:
708
+ return "null"
709
+
710
+ if isinstance(val, bool):
711
+ return "true" if val else "false"
712
+
713
+ if isinstance(val, (int, float)):
714
+ if isinstance(val, float) and (math.isnan(val) or math.isinf(val)):
715
+ return "null"
716
+ return str(val)
717
+
718
+ if isinstance(val, Decimal):
719
+ if val.is_nan() or val.is_infinite():
720
+ return "null"
721
+ return str(val)
722
+
723
+ # Handle strings, bytes, and bytearrays as scalars (not Sequences)
724
+ if isinstance(val, (str, bytes, bytearray)):
725
+ if isinstance(val, (bytes, bytearray)):
726
+ val = val.decode("utf-8", errors="replace")
727
+ return json.dumps(val)
728
+
729
+ if isinstance(val, Mapping):
730
+ val_id = id(val)
731
+ if val_id in seen:
732
+ return circular_placeholder
733
+
734
+ seen.add(val_id)
735
+ try:
736
+ entries: list[str] = []
737
+ for k, v in val.items():
738
+ formatted_val = stringify(v)
739
+ if formatted_val is not None:
740
+ formatted_key = json.dumps(str(k))
741
+ entries.append(f"{formatted_key}=>{formatted_val}")
742
+ return "{" + ", ".join(entries) + "}"
743
+ finally:
744
+ seen.remove(val_id)
745
+
746
+ if isinstance(val, Sequence):
747
+ val_id = id(val)
748
+ if val_id in seen:
749
+ return circular_placeholder
750
+
751
+ seen.add(val_id)
752
+ try:
753
+ items: list[str] = []
754
+ for item in val:
755
+ formatted_val = stringify(item)
756
+ items.append("null" if formatted_val is None else formatted_val)
757
+ return "[" + ", ".join(items) + "]"
758
+ finally:
759
+ seen.remove(val_id)
760
+
761
+ # Fallback for custom objects
762
+ return json.dumps(str(val))
763
+
764
+ result = stringify(obj)
765
+ return "null" if result is None else result
766
+
767
+
768
+ def _flatten(it: Sequence[object], level: int = 5) -> list[object]:
769
+
770
+ def flatten_(it: Sequence[object], level: int = 5) -> Generator[object]:
771
+ for obj in it:
772
+ if level < 1 or not isinstance(obj, (list, tuple)):
773
+ yield obj
774
+ else:
775
+ yield from flatten_(obj, level=level - 1)
776
+
777
+ return list(flatten_(it, level))