Skip to content

Commit 33f01c6

Browse files
committed
Support for trim_blocks and lstrip_blocks for comments
1 parent 13cc443 commit 33f01c6

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

adafruit_templateengine.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,14 +325,35 @@ def _find_block_comment(template: str):
325325
return _PRECOMPILED_BLOCK_COMMENT_PATTERN.search(template)
326326

327327

328-
def _remove_comments(template: str):
328+
def _remove_comments(
329+
template: str,
330+
*,
331+
trim_blocks: bool = True,
332+
lstrip_blocks: bool = True,
333+
):
334+
def _remove_matched_comment(template: str, comment_match: re.Match):
335+
text_before_comment = template[: comment_match.start()]
336+
text_after_comment = template[comment_match.end() :]
337+
338+
if text_before_comment:
339+
if lstrip_blocks:
340+
if _token_is_on_own_line(text_before_comment):
341+
text_before_comment = text_before_comment.rstrip(" ")
342+
343+
if text_after_comment:
344+
if trim_blocks:
345+
if text_after_comment.startswith("\n"):
346+
text_after_comment = text_after_comment[1:]
347+
348+
return text_before_comment + text_after_comment
349+
329350
# Remove hash comments: {# ... #}
330351
while (comment_match := _find_hash_comment(template)) is not None:
331-
template = template[: comment_match.start()] + template[comment_match.end() :]
352+
template = _remove_matched_comment(template, comment_match)
332353

333354
# Remove block comments: {% comment %} ... {% endcomment %}
334355
while (comment_match := _find_block_comment(template)) is not None:
335-
template = template[: comment_match.start()] + template[comment_match.end() :]
356+
template = _remove_matched_comment(template, comment_match)
336357

337358
return template
338359

0 commit comments

Comments
 (0)