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
@@ -1,371 +0,0 @@
1
- """The built-in _render_ tag."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- from typing import TYPE_CHECKING
7
- from typing import Iterable
8
- from typing import Optional
9
- from typing import TextIO
10
- from typing import Union
11
-
12
- from liquid.ast import Node
13
- from liquid.ast import Partial
14
- from liquid.ast import PartialScope
15
- from liquid.builtin.drops import IterableDrop
16
- from liquid.builtin.expressions import Identifier
17
- from liquid.builtin.expressions import KeywordArgument
18
- from liquid.builtin.expressions import Literal
19
- from liquid.builtin.expressions import Path
20
- from liquid.builtin.expressions import StringLiteral
21
- from liquid.builtin.expressions import parse_identifier
22
- from liquid.builtin.expressions import parse_primitive
23
- from liquid.builtin.tags.for_tag import ForLoop
24
- from liquid.builtin.tags.include_tag import TAG_INCLUDE
25
- from liquid.exceptions import LiquidSyntaxError
26
- from liquid.exceptions import TemplateNotFoundError
27
- from liquid.tag import Tag
28
- from liquid.template import BoundTemplate
29
- from liquid.token import TOKEN_AS
30
- from liquid.token import TOKEN_FOR
31
- from liquid.token import TOKEN_TAG
32
- from liquid.token import TOKEN_WITH
33
- from liquid.token import TOKEN_WORD
34
- from liquid.token import Token
35
- from liquid.utils import ReadOnlyChainMap
36
-
37
- if TYPE_CHECKING:
38
- from liquid.context import RenderContext
39
- from liquid.expression import Expression
40
- from liquid.stream import TokenStream
41
-
42
-
43
- TAG_RENDER = sys.intern("render")
44
-
45
-
46
- class RenderNode(Node):
47
- """The built-in _render_ tag."""
48
-
49
- __slots__ = ("name", "var", "loop", "alias", "args")
50
- tag = TAG_RENDER
51
-
52
- def __init__(
53
- self,
54
- token: Token,
55
- name: Union[StringLiteral, Identifier],
56
- *,
57
- var: Optional[Expression] = None,
58
- loop: bool = False,
59
- alias: Optional[Identifier] = None,
60
- args: Optional[list[KeywordArgument]] = None,
61
- ):
62
- super().__init__(token)
63
- self.name = name
64
- self.var = var
65
- self.loop = loop
66
- self.alias = alias
67
- self.args = args or []
68
- self.blank = False
69
-
70
- def __str__(self) -> str:
71
- var = ""
72
- if self.var:
73
- var = f" for {self.var}" if self.loop else f" with {self.var}"
74
- if self.alias:
75
- var += f" as {self.alias}"
76
- if self.args:
77
- var += ","
78
- args = " " + ", ".join(str(arg) for arg in self.args) if self.args else ""
79
- return f"{{% render {self.name}{var}{args} %}}"
80
-
81
- def render_to_output(self, context: RenderContext, buffer: TextIO) -> int:
82
- """Render the node to the output buffer."""
83
- if isinstance(self.name, Identifier):
84
- # We're expecting an inline snippet.
85
- template: Optional[BoundTemplate] = context.resolve(
86
- self.name, token=self.token, default=None
87
- )
88
- if not isinstance(template, BoundTemplate):
89
- raise TemplateNotFoundError(
90
- self.name,
91
- filename=context.template.full_name(),
92
- token=self.name.token,
93
- )
94
- else:
95
- try:
96
- template = context.env.get_template(
97
- self.name.value, context=context, tag=self.tag
98
- )
99
- except TemplateNotFoundError as err:
100
- err.token = self.name.token
101
- err.template_name = context.template.full_name()
102
- raise
103
-
104
- # Evaluate keyword arguments once. Unlike 'include', 'render' can not
105
- # mutate variables in the outer scope, so there's no need to re-evaluate
106
- # arguments for each loop (if any).
107
- args = {arg.name: arg.value.evaluate(context) for arg in self.args}
108
-
109
- # We're using a chain map here in case we need to push a forloop drop into
110
- # it. As drops are read only, the built-in collections.ChainMap will not do.
111
- namespace = ReadOnlyChainMap(args)
112
-
113
- # New context with globals and filters from the parent, plus the read only
114
- # namespace containing render arguments and bound variable.
115
- ctx = context.copy(
116
- namespace,
117
- disabled_tags=[TAG_INCLUDE],
118
- carry_loop_iterations=True,
119
- template=template,
120
- )
121
-
122
- # Optionally bind a variable to the render namespace.
123
- if self.var is not None:
124
- val = self.var.evaluate(context)
125
- key = self.alias or template.name.split(".")[0]
126
-
127
- # If the variable is array-like, render the template once for each item.
128
- # `self.loop` being True indicates the render expression used "for" not
129
- # "with". This distinction is not made when using the 'include' tag.
130
- if self.loop and isinstance(val, (tuple, list, IterableDrop)):
131
- ctx.raise_for_loop_limit(len(val))
132
- forloop = ForLoop(
133
- name=key,
134
- it=iter(val),
135
- length=len(val),
136
- parentloop=context.env.undefined("parentloop", token=self.token),
137
- )
138
-
139
- args["forloop"] = forloop
140
- args[key] = None
141
-
142
- for itm in forloop:
143
- args[key] = itm
144
- template.render_with_context(
145
- ctx, buffer, partial=True, block_scope=True
146
- )
147
- else:
148
- # The bound variable is not array-like, shove it into the namespace
149
- # via args.
150
- args[key] = val
151
- template.render_with_context(
152
- ctx, buffer, partial=True, block_scope=True
153
- )
154
- else:
155
- template.render_with_context(ctx, buffer, partial=True, block_scope=True)
156
-
157
- return True
158
-
159
- async def render_to_output_async(
160
- self, context: RenderContext, buffer: TextIO
161
- ) -> int:
162
- """Render the node to the output buffer."""
163
- if isinstance(self.name, Identifier):
164
- # We're expecting an inline snippet.
165
- template: Optional[BoundTemplate] = context.resolve(
166
- self.name, token=self.token, default=None
167
- )
168
- if not isinstance(template, BoundTemplate):
169
- raise TemplateNotFoundError(
170
- self.name,
171
- filename=context.template.full_name(),
172
- token=self.name.token,
173
- )
174
- else:
175
- try:
176
- template = await context.env.get_template_async(
177
- self.name.value, context=context, tag=self.tag
178
- )
179
- except TemplateNotFoundError as err:
180
- err.token = self.name.token
181
- err.template_name = context.template.full_name()
182
- raise
183
-
184
- # Evaluate keyword arguments once. Unlike 'include', 'render' can not
185
- # mutate variables in the outer scope, so there's no need to re-evaluate
186
- # arguments for each loop (if any).
187
- args = {arg.name: await arg.value.evaluate_async(context) for arg in self.args}
188
-
189
- # We're using a chain map here in case we need to push a forloop drop into
190
- # it. As drops are read only, the built-in collections.ChainMap will not do.
191
- namespace = ReadOnlyChainMap(args)
192
-
193
- # New context with globals and filters from the parent, plus the read only
194
- # namespace containing render arguments and bound variable.
195
- ctx = context.copy(
196
- namespace,
197
- disabled_tags=[TAG_INCLUDE],
198
- carry_loop_iterations=True,
199
- template=template,
200
- )
201
-
202
- # Optionally bind a variable to the render namespace.
203
- if self.var is not None:
204
- val = await self.var.evaluate_async(context)
205
- key = self.alias or template.name.split(".")[0]
206
-
207
- # If the variable is array-like, render the template once for each item.
208
- # `self.loop` being True indicates the render expression used "for" not
209
- # "with". This distinction is not made when using the 'include' tag.
210
- if self.loop and isinstance(val, (tuple, list, IterableDrop)):
211
- ctx.raise_for_loop_limit(len(val))
212
- forloop = ForLoop(
213
- name=key,
214
- it=iter(val),
215
- length=len(val),
216
- parentloop=context.env.undefined("parentloop", token=self.token),
217
- )
218
-
219
- args["forloop"] = forloop
220
- args[key] = None
221
-
222
- for itm in forloop:
223
- args[key] = itm
224
- await template.render_with_context_async(
225
- ctx, buffer, partial=True, block_scope=True
226
- )
227
- else:
228
- # The bound variable is not array-like, shove it into the namespace
229
- # via args.
230
- args[key] = val
231
- await template.render_with_context_async(
232
- ctx, buffer, partial=True, block_scope=True
233
- )
234
- else:
235
- await template.render_with_context_async(
236
- ctx, buffer, partial=True, block_scope=True
237
- )
238
-
239
- return True
240
-
241
- def children(
242
- self, static_context: RenderContext, *, include_partials: bool = True
243
- ) -> Iterable[Node]:
244
- """Return this node's children."""
245
- if isinstance(self.name, Identifier):
246
- # We're expecting an inline snippet.
247
- # Always visit inline snippets, even if include_partials is False.
248
- template: Optional[BoundTemplate] = static_context.resolve(
249
- self.name, token=self.token, default=None
250
- )
251
- if template:
252
- yield from template.nodes
253
- elif include_partials:
254
- name = self.name.evaluate(static_context)
255
- try:
256
- template = static_context.env.get_template(
257
- str(name), context=static_context, tag=self.tag
258
- )
259
- yield from template.nodes
260
- except TemplateNotFoundError as err:
261
- err.token = self.name.token
262
- err.template_name = static_context.template.full_name()
263
- raise
264
-
265
- async def children_async(
266
- self, static_context: RenderContext, *, include_partials: bool = True
267
- ) -> Iterable[Node]:
268
- """Return this node's children."""
269
- if isinstance(self.name, Identifier):
270
- # We're expecting an inline snippet.
271
- template: Optional[BoundTemplate] = static_context.resolve(
272
- self.name, token=self.token, default=None
273
- )
274
- if template:
275
- return template.nodes
276
- elif include_partials:
277
- name = await self.name.evaluate_async(static_context)
278
- try:
279
- template = await static_context.env.get_template_async(
280
- str(name), context=static_context, tag=self.tag
281
- )
282
- return template.nodes
283
- except TemplateNotFoundError as err:
284
- err.token = self.name.token
285
- err.template_name = static_context.template.full_name()
286
- raise
287
- return []
288
-
289
- def expressions(self) -> Iterable[Expression]:
290
- """Return this node's expressions."""
291
- if self.var:
292
- yield self.var
293
- yield from (arg.value for arg in self.args)
294
-
295
- def partial_scope(self) -> Optional[Partial]:
296
- """Return information about a partial template loaded by this node."""
297
- scope: list[Identifier] = [
298
- Identifier(arg.name, token=arg.token) for arg in self.args
299
- ]
300
-
301
- if self.var:
302
- if self.alias:
303
- scope.append(self.alias)
304
- elif isinstance(self.name, Literal):
305
- scope.append(
306
- Identifier(
307
- str(self.name.value).split(".", 1)[0], token=self.name.token
308
- )
309
- )
310
-
311
- partial_name = self.name.value if isinstance(self.name, StringLiteral) else ""
312
- partial_key = hash((partial_name, *[arg.name for arg in self.args]))
313
-
314
- # Static analysis will use the parent template name if Partial.name is
315
- # empty. Which is what we want for inline snippets.
316
- return Partial(
317
- name=partial_name,
318
- scope=PartialScope.ISOLATED,
319
- in_scope=scope,
320
- key=partial_key,
321
- )
322
-
323
-
324
- BIND_TAGS = frozenset((TOKEN_WITH, TOKEN_FOR))
325
-
326
-
327
- class RenderTag(Tag):
328
- """The built-in _render_ tag."""
329
-
330
- name = TAG_RENDER
331
- block = False
332
- node_class = RenderNode
333
-
334
- def parse(self, stream: TokenStream) -> Node:
335
- """Parse tokens from _stream_ into an AST node."""
336
- token = stream.eat(TOKEN_TAG)
337
- tokens = stream.into_inner(tag=token, eat=False)
338
- name: Union[Expression, Identifier] = parse_primitive(self.env, tokens)
339
-
340
- if isinstance(name, Path):
341
- head = name.head()
342
- if len(name.path) != 1 or not isinstance(head, str):
343
- raise LiquidSyntaxError(
344
- "expected an identifier, found a path",
345
- token=name.token,
346
- )
347
- name = Identifier(head, token=name.token)
348
- elif not isinstance(name, StringLiteral):
349
- raise LiquidSyntaxError("expected a string or identifier", token=name.token)
350
-
351
- alias: Optional[Identifier] = None
352
- var: Optional[Path] = None
353
- loop: bool = False
354
-
355
- # Optionally bind a variable to the included template context
356
- if tokens.current.kind in BIND_TAGS:
357
- loop = tokens.current.kind == TOKEN_FOR
358
- next(tokens) # Eat 'with' or 'for'
359
- tokens.expect(TOKEN_WORD)
360
- var = Path.parse(self.env, tokens)
361
-
362
- # The bound variable will take the name of the template by default,
363
- # or an alias if an identifier follows the "as" keyword.
364
- if tokens.current.kind == TOKEN_AS:
365
- next(tokens) # Eat 'as'
366
- tokens.expect(TOKEN_WORD)
367
- alias = parse_identifier(self.env, tokens)
368
-
369
- # Zero or more keyword arguments
370
- args = KeywordArgument.parse(self.env, tokens)
371
- return self.node_class(token, name, var=var, loop=loop, alias=alias, args=args)
@@ -1,320 +0,0 @@
1
- """The built-in _tablerow_ tag."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- from typing import TYPE_CHECKING
7
- from typing import Any
8
- from typing import Iterable
9
- from typing import Iterator
10
- from typing import Mapping
11
- from typing import TextIO
12
-
13
- from liquid.ast import BlockNode
14
- from liquid.ast import Node
15
- from liquid.builtin.expressions import Identifier
16
- from liquid.builtin.expressions import LoopExpression
17
- from liquid.exceptions import BreakLoop
18
- from liquid.exceptions import ContinueLoop
19
- from liquid.limits import to_int
20
- from liquid.parser import get_parser
21
- from liquid.tag import Tag
22
- from liquid.token import TOKEN_TAG
23
- from liquid.token import Token
24
-
25
- if TYPE_CHECKING:
26
- from liquid.context import RenderContext
27
- from liquid.expression import Expression
28
- from liquid.stream import TokenStream
29
-
30
-
31
- TAG_TABLEROW = sys.intern("tablerow")
32
- TAG_ENDTABLEROW = sys.intern("endtablerow")
33
-
34
- END_TAGBLOCK = frozenset((TAG_ENDTABLEROW,))
35
-
36
-
37
- class TableRow(Mapping[str, object]):
38
- """Table row helper variables."""
39
-
40
- __slots__ = (
41
- "name",
42
- "it",
43
- "length",
44
- "ncols",
45
- "_index",
46
- "_row",
47
- "_col",
48
- )
49
-
50
- _keys = frozenset(
51
- [
52
- "length",
53
- "index",
54
- "index0",
55
- "rindex",
56
- "rindex0",
57
- "first",
58
- "last",
59
- "col",
60
- "col0",
61
- "col_first",
62
- "col_last",
63
- "row",
64
- ]
65
- )
66
-
67
- def __init__(self, name: str, it: Iterator[Any], length: int, ncols: int) -> None:
68
- self.name = name
69
- self.it = it
70
- self.length = length
71
- self.ncols = ncols
72
- self._index = -1
73
- self._row = 1
74
- self._col = 0
75
-
76
- def __repr__(self) -> str: # pragma: no cover
77
- return f"TableRow(name='{self.name}', length={self.length})"
78
-
79
- def __getitem__(self, key: str) -> object:
80
- if key in self._keys:
81
- return getattr(self, key)
82
- raise KeyError(key)
83
-
84
- def __len__(self) -> int:
85
- return len(self._keys)
86
-
87
- def __iter__(self) -> Iterator[Any]:
88
- return self
89
-
90
- def __next__(self) -> object:
91
- self.step()
92
- return next(self.it)
93
-
94
- @property
95
- def index(self) -> int:
96
- """The 1-based index of the current loop iteration."""
97
- return self._index + 1
98
-
99
- @property
100
- def index0(self) -> int:
101
- """The 0-based index of the current loop iteration."""
102
- return self._index
103
-
104
- @property
105
- def rindex(self) -> int:
106
- """The 1-based index, counting from the right, of the current loop iteration."""
107
- return self.length - self._index
108
-
109
- @property
110
- def rindex0(self) -> int:
111
- """The 0-based index, counting from the right, of the current loop iteration."""
112
- return self.length - self._index - 1
113
-
114
- @property
115
- def first(self) -> bool:
116
- """True if this is the first iteration, false otherwise."""
117
- return self._index == 0
118
-
119
- @property
120
- def last(self) -> bool:
121
- """True if this is the last iteration, false otherwise."""
122
- return self._index == self.length - 1
123
-
124
- @property
125
- def col(self) -> int:
126
- """The 1-based index of the current column."""
127
- return self._col
128
-
129
- @property
130
- def col0(self) -> int:
131
- """The 0-based index of the current column."""
132
- return self._col - 1
133
-
134
- @property
135
- def col_first(self) -> bool:
136
- """True if this is the first column. False otherwise."""
137
- return self._col == 1
138
-
139
- @property
140
- def col_last(self) -> bool:
141
- """True if this is the last iteration, false otherwise."""
142
- return self._col == self.ncols
143
-
144
- @property
145
- def row(self) -> int:
146
- """The current row number."""
147
- return self._row
148
-
149
- def step(self) -> None:
150
- """Step the forloop forward."""
151
- self._index += 1
152
- if self._col == self.ncols:
153
- self._col = 1
154
- self._row += 1
155
- else:
156
- self._col += 1
157
-
158
-
159
- class TablerowNode(Node):
160
- """The built-in _tablerow_ tag."""
161
-
162
- interrupts = True
163
- """If _true_, handle `break` and `continue` interrupts inside a tablerow loop."""
164
-
165
- __slots__ = ("expression", "block")
166
-
167
- def __init__(
168
- self,
169
- token: Token,
170
- expression: LoopExpression,
171
- block: BlockNode,
172
- ):
173
- super().__init__(token)
174
- self.expression = expression
175
- self.block = block
176
- self.blank = False
177
-
178
- def __str__(self) -> str:
179
- return f"tablerow({self.expression}) {{ {self.block} }}"
180
-
181
- def _int_or_zero(self, arg: object) -> int:
182
- try:
183
- return to_int(arg)
184
- except ValueError:
185
- return 0
186
-
187
- def render_to_output(self, context: RenderContext, buffer: TextIO) -> int:
188
- """Return this node's children."""
189
- name = self.expression.identifier
190
- loop_iter, length = self.expression.evaluate(context)
191
-
192
- if not length:
193
- # An empty iterable renders no rows.
194
- return True
195
-
196
- if self.expression.cols:
197
- cols = self._int_or_zero(self.expression.cols.evaluate(context))
198
- else:
199
- cols = length
200
-
201
- context.raise_for_loop_limit(length)
202
- tablerow = TableRow(name, loop_iter, length, cols)
203
-
204
- namespace: dict[str, object] = {
205
- "tablerowloop": tablerow,
206
- }
207
-
208
- buffer.write('<tr class="row1">\n')
209
- _break = False
210
-
211
- with context.loop(namespace, tablerow):
212
- for item in tablerow:
213
- namespace[name] = item
214
- buffer.write(f'<td class="col{tablerow.col}">')
215
-
216
- try:
217
- self.block.render(context=context, buffer=buffer)
218
- except BreakLoop:
219
- if self.interrupts:
220
- _break = True
221
- else:
222
- raise
223
- except ContinueLoop:
224
- if not self.interrupts:
225
- raise
226
-
227
- buffer.write("</td>")
228
-
229
- if tablerow.col_last and not tablerow.last:
230
- buffer.write(f'</tr>\n<tr class="row{tablerow.row + 1}">')
231
-
232
- if _break:
233
- break
234
-
235
- buffer.write("</tr>\n")
236
- return True
237
-
238
- async def render_to_output_async(
239
- self, context: RenderContext, buffer: TextIO
240
- ) -> int:
241
- """Return this node's children."""
242
- name = self.expression.identifier
243
- loop_iter, length = await self.expression.evaluate_async(context)
244
-
245
- if self.expression.cols:
246
- cols = self._int_or_zero(await self.expression.cols.evaluate_async(context))
247
- else:
248
- cols = length
249
-
250
- context.raise_for_loop_limit(length)
251
- tablerow = TableRow(name, loop_iter, length, cols)
252
-
253
- namespace: dict[str, object] = {
254
- "tablerowloop": tablerow,
255
- }
256
-
257
- buffer.write('<tr class="row1">\n')
258
- _break = False
259
-
260
- with context.extend(namespace):
261
- for item in tablerow:
262
- namespace[name] = item
263
- buffer.write(f'<td class="col{tablerow.col}">')
264
-
265
- try:
266
- await self.block.render_async(context=context, buffer=buffer)
267
- except BreakLoop:
268
- if self.interrupts:
269
- _break = True
270
- else:
271
- raise
272
- except ContinueLoop:
273
- if not self.interrupts:
274
- raise
275
-
276
- buffer.write("</td>")
277
-
278
- if tablerow.col_last and not tablerow.last:
279
- buffer.write(f'</tr>\n<tr class="row{tablerow.row + 1}">')
280
-
281
- if _break:
282
- break
283
-
284
- buffer.write("</tr>\n")
285
- return True
286
-
287
- def children(
288
- self,
289
- static_context: RenderContext, # noqa: ARG002
290
- *,
291
- include_partials: bool = True, # noqa: ARG002
292
- ) -> Iterable[Node]:
293
- """Return this node's children."""
294
- yield self.block
295
-
296
- def expressions(self) -> Iterable[Expression]:
297
- """Return this node's expressions."""
298
- yield self.expression
299
-
300
- def block_scope(self) -> Iterable[Identifier]:
301
- """Return variables this node adds to the node's block scope."""
302
- yield Identifier(self.expression.identifier, token=self.expression.token)
303
- yield Identifier("tablerowloop", token=self.token)
304
-
305
-
306
- class TablerowTag(Tag):
307
- """The built-in _tablerow_ tag."""
308
-
309
- name = TAG_TABLEROW
310
- end = TAG_ENDTABLEROW
311
- node_class = TablerowNode
312
-
313
- def parse(self, stream: TokenStream) -> TablerowNode:
314
- """Parse tokens from _stream_ into an AST node."""
315
- token = stream.eat(TOKEN_TAG)
316
- tokens = stream.into_inner(tag=token)
317
- expr = LoopExpression.parse(self.env, tokens)
318
- block = get_parser(self.env).parse_block(stream, END_TAGBLOCK)
319
- stream.expect(TOKEN_TAG, value=TAG_ENDTABLEROW)
320
- return self.node_class(token, expression=expr, block=block)