From: Kevin Date: Wed, 13 May 2020 02:10:49 +0000 (-0400) Subject: Add support for parsing `{% else %}` blocks in for loops X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=e8689ca98ccbb6748945f30d82b28dfa6a2f084f;p=thirdparty%2Fjinja.git Add support for parsing `{% else %}` blocks in for loops --- diff --git a/1 b/1 new file mode 100644 index 00000000..e69de29b diff --git a/2 b/2 new file mode 100644 index 00000000..e69de29b diff --git a/new_parser.py b/new_parser.py index b3dd8ac9..5e3b0c5c 100644 --- a/new_parser.py +++ b/new_parser.py @@ -143,7 +143,7 @@ def parse_block_extends(ast): def parse_block_for(ast): target = None iter = None - body = parse(ast['contents']) + body = ast['contents'] else_ = [] test = None recursive = False @@ -174,8 +174,15 @@ def parse_block_for(ast): if len(block_parameters) > 1: recursive = block_parameters[-1]['value']['variable'] == 'recursive' + else_ = _split_contents_at_block(ast['contents'], 'else') + + if else_ is not None: + body, _, else_ = else_ + else: + else_ = [] + return nodes.For( - target, iter, body, else_, test, recursive, + target, iter, parse(body), parse(else_), test, recursive, lineno=lineno_from_parseinfo(ast['parseinfo']) ) @@ -677,4 +684,14 @@ def _parse_import_context(block_parameters): if block_parameters[-2]['value']['variable'] not in ['with', 'without']: return None - return block_parameters[-2]['value']['variable'] == 'with' \ No newline at end of file + return block_parameters[-2]['value']['variable'] == 'with' + +def _split_contents_at_block(contents, block_name): + for index, expression in enumerate(contents): + if 'block' in expression: + block = parse_block(expression) + + if expression['block']['name'] == block_name: + return (contents[:index], block, contents[index + 1:]) + + return None diff --git a/test_template.jinja b/test_template.jinja index 399f898f..ac5fa1b6 100644 --- a/test_template.jinja +++ b/test_template.jinja @@ -77,4 +77,9 @@ across lines #} {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} {% include "sidebar.html" ignore missing %} {% include "sidebar.html" ignore missing with context %} -{% include "sidebar.html" ignore missing without context %} \ No newline at end of file +{% include "sidebar.html" ignore missing without context %} +{% for item in seq %} + {{ item }} +{% else %} + did not iterate +{% endfor %} \ No newline at end of file