Add support for parsing {% else %} blocks in for loops

This commit is contained in:
Kevin 2020-05-12 22:10:49 -04:00
parent 00e950e831
commit e8689ca98c
4 changed files with 26 additions and 4 deletions

0
1 Normal file
View File

0
2 Normal file
View File

View File

@ -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'
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

View File

@ -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 %}
{% include "sidebar.html" ignore missing without context %}
{% for item in seq %}
{{ item }}
{% else %}
did not iterate
{% endfor %}