Skip to content

Commit e117e3e

Browse files
committed
Refactor of indenting template function parts
1 parent 01a2a34 commit e117e3e

File tree

1 file changed

+33
-48
lines changed

1 file changed

+33
-48
lines changed

adafruit_templateengine.py

Lines changed: 33 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def _replace_amp_or_semi(match: re.Match):
194194
r"{% comment ('.*?' |\".*?\" )?%}[\s\S]*?{% endcomment %}"
195195
)
196196
_TOKEN_PATTERN = re.compile(r"{{ .+? }}|{% .+? %}")
197-
_LSTRIP_BLOCK_PATTERN = re.compile(r"\n( )+$")
197+
_LSTRIP_BLOCK_PATTERN = re.compile(r"\n +$")
198198

199199

200200
def _find_extends(template: str):
@@ -476,8 +476,12 @@ def _create_template_rendering_function( # pylint: disable=,too-many-locals,too
476476
template = _remove_comments(template)
477477

478478
# Create definition of the template function
479-
function_string = f"def {function_name}({context_name}):\n"
480-
indent, indentation_level = " ", 1
479+
function_def = f"def {function_name}({context_name}):\n"
480+
indent_level = 1
481+
482+
def indented(fragment: str, end: str = "\n") -> str:
483+
nonlocal indent_level
484+
return " " * indent_level + fragment + end
481485

482486
# Keep track of the template state
483487
nested_if_statements: "list[Token]" = []
@@ -506,11 +510,9 @@ def _create_template_rendering_function( # pylint: disable=,too-many-locals,too
506510
text_before_token = text_before_token[1:]
507511

508512
if text_before_token:
509-
function_string += (
510-
indent * indentation_level + f"yield {repr(text_before_token)}\n"
511-
)
513+
function_def += indented(f"yield {repr(text_before_token)}")
512514
else:
513-
function_string += indent * indentation_level + "pass\n"
515+
function_def += indented("pass")
514516

515517
# Token is an expression
516518
if token.content.startswith(r"{{ "):
@@ -523,97 +525,82 @@ def _create_template_rendering_function( # pylint: disable=,too-many-locals,too
523525

524526
# Expression should be escaped
525527
if autoescape:
526-
function_string += (
527-
indent * indentation_level
528-
+ f"yield safe_html({token.content[3:-3]})\n"
529-
)
528+
function_def += indented(f"yield safe_html({token.content[3:-3]})")
530529
# Expression should not be escaped
531530
else:
532-
function_string += (
533-
indent * indentation_level + f"yield str({token.content[3:-3]})\n"
534-
)
531+
function_def += indented(f"yield {token.content[3:-3]}")
535532

536533
# Token is a statement
537534
elif token.content.startswith(r"{% "):
538535
last_token_was_block = True
539536

540537
# Token is a some sort of if statement
541538
if token.content.startswith(r"{% if "):
542-
function_string += (
543-
indent * indentation_level + f"{token.content[3:-3]}:\n"
544-
)
545-
indentation_level += 1
539+
function_def += indented(f"if {token.content[6:-3]}:")
540+
indent_level += 1
546541

547542
nested_if_statements.append(token)
548543
elif token.content.startswith(r"{% elif "):
549544
if not nested_if_statements:
550545
raise TemplateSyntaxError(token, "No matching {% if ... %}")
551546

552-
indentation_level -= 1
553-
function_string += (
554-
indent * indentation_level + f"{token.content[3:-3]}:\n"
555-
)
556-
indentation_level += 1
547+
indent_level -= 1
548+
function_def += indented(f"elif {token.content[8:-3]}:")
549+
indent_level += 1
557550
elif token.content == r"{% else %}":
558551
if not nested_if_statements:
559552
raise TemplateSyntaxError(token, "No matching {% if ... %}")
560553

561-
indentation_level -= 1
562-
function_string += indent * indentation_level + "else:\n"
563-
indentation_level += 1
554+
indent_level -= 1
555+
function_def += indented("else:")
556+
indent_level += 1
564557
elif token.content == r"{% endif %}":
565558
if not nested_if_statements:
566559
raise TemplateSyntaxError(token, "No matching {% if ... %}")
567560

568-
indentation_level -= 1
561+
indent_level -= 1
569562
nested_if_statements.pop()
570563

571564
# Token is a for loop
572565
elif token.content.startswith(r"{% for "):
573-
function_string += (
574-
indent * indentation_level + f"{token.content[3:-3]}:\n"
575-
)
576-
indentation_level += 1
566+
function_def += indented(f"for {token.content[7:-3]}:")
567+
indent_level += 1
577568

578569
nested_for_loops.append(token)
579570
elif token.content == r"{% empty %}":
580571
if not nested_for_loops:
581572
raise TemplateSyntaxError(token, "No matching {% for ... %}")
582573

583-
indentation_level -= 1
584574
last_forloop_iterable = (
585575
nested_for_loops[-1].content[3:-3].split(" in ", 1)[1]
586576
)
587-
function_string += (
588-
indent * indentation_level + f"if not {last_forloop_iterable}:\n"
589-
)
590-
indentation_level += 1
577+
578+
indent_level -= 1
579+
function_def += indented(f"if not {last_forloop_iterable}:")
580+
indent_level += 1
591581
elif token.content == r"{% endfor %}":
592582
if not nested_for_loops:
593583
raise TemplateSyntaxError(token, "No matching {% for ... %}")
594584

595-
indentation_level -= 1
585+
indent_level -= 1
596586
nested_for_loops.pop()
597587

598588
# Token is a while loop
599589
elif token.content.startswith(r"{% while "):
600-
function_string += (
601-
indent * indentation_level + f"{token.content[3:-3]}:\n"
602-
)
603-
indentation_level += 1
590+
function_def += indented(f"while {token.content[9:-3]}:")
591+
indent_level += 1
604592

605593
nested_while_loops.append(token)
606594
elif token.content == r"{% endwhile %}":
607595
if not nested_while_loops:
608596
raise TemplateSyntaxError(token, "No matching {% while ... %}")
609597

610-
indentation_level -= 1
598+
indent_level -= 1
611599
nested_while_loops.pop()
612600

613601
# Token is a Python code
614602
elif token.content.startswith(r"{% exec "):
615-
expression = token.content[8:-3]
616-
function_string += indent * indentation_level + f"{expression}\n"
603+
function_def += indented(f"{token.content[8:-3]}")
617604

618605
# Token is a autoescape mode change
619606
elif token.content.startswith(r"{% autoescape "):
@@ -668,12 +655,10 @@ def _create_template_rendering_function( # pylint: disable=,too-many-locals,too
668655
if trim_blocks and text_after_last_token.startswith("\n"):
669656
text_after_last_token = text_after_last_token[1:]
670657

671-
function_string += (
672-
indent * indentation_level + f"yield {repr(text_after_last_token)}\n"
673-
)
658+
function_def += indented(f"yield {repr(text_after_last_token)}")
674659

675660
# Create and return the template function
676-
exec(function_string) # pylint: disable=exec-used
661+
exec(function_def) # pylint: disable=exec-used
677662
return locals()[function_name]
678663

679664

0 commit comments

Comments
 (0)