Implement {% block ... %}

This commit is contained in:
RunasSudo 2025-05-14 18:26:54 +10:00
parent 8e833c85c8
commit 21b5295cf3
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
2 changed files with 24 additions and 5 deletions

View File

@ -45,6 +45,16 @@ class Emitter:
raise NotImplementedError() raise NotImplementedError()
def start_block(self, block_name: str) -> None:
"""Called at {% block ... %}"""
self.emit('void ' + block_name + '(void) {')
def end_block(self) -> None:
"""Called at {% endblock %}"""
self.emit('}')
def start_page(self, page_name: str) -> None: def start_page(self, page_name: str) -> None:
"""Called at {% page ... %}""" """Called at {% page ... %}"""

View File

@ -27,7 +27,7 @@ class Parser:
self.cur_line_contains_handlebars = False self.cur_line_contains_handlebars = False
self.cur_line_contains_nonblank_literal = False self.cur_line_contains_nonblank_literal = False
self.cur_line_leading_ws = '' # Buffer for leading whitespace self.cur_line_leading_ws = '' # Buffer for leading whitespace
self.in_page = False self.in_html = False
def parse(self) -> None: def parse(self) -> None:
"""Parse the entire file""" """Parse the entire file"""
@ -70,15 +70,24 @@ class Parser:
command = s[len('{%'):-len('%}')].strip() command = s[len('{%'):-len('%}')].strip()
if command.startswith('page '): if command.startswith('block '):
# {% block ... %}
block_name = command[len('block '):].strip()
self.emitter.start_block(block_name)
self.in_html = True
elif command == 'endblock':
# {% endblock %}
self.emitter.end_block()
self.in_html = False
elif command.startswith('page '):
# {% page ... %} # {% page ... %}
page_name = command[len('page '):].strip() page_name = command[len('page '):].strip()
self.emitter.start_page(page_name) self.emitter.start_page(page_name)
self.in_page = True self.in_html = True
elif command == 'endpage': elif command == 'endpage':
# {% endpage %} # {% endpage %}
self.emitter.end_page() self.emitter.end_page()
self.in_page = False self.in_html = False
else: else:
raise SyntaxError(f'Unknown command "{command}"') raise SyntaxError(f'Unknown command "{command}"')
@ -134,7 +143,7 @@ class Parser:
s = self.buffer[:stop_reading_idx] s = self.buffer[:stop_reading_idx]
self.buffer = self.buffer[stop_reading_idx:] self.buffer = self.buffer[stop_reading_idx:]
if not self.in_page: if not self.in_html:
# Not in a page block! # Not in a page block!
if s.isspace(): if s.isspace():
# Suppress whitespace outside page blocks # Suppress whitespace outside page blocks