NDOJ/judge/jinja2/spaceless.py

33 lines
1 KiB
Python
Raw Normal View History

2020-01-21 06:35:58 +00:00
import re
2022-09-16 23:02:53 +00:00
from jinja2 import nodes
2020-01-21 06:35:58 +00:00
from jinja2.ext import Extension
2022-09-16 23:02:53 +00:00
from markupsafe import Markup
2020-01-21 06:35:58 +00:00
class SpacelessExtension(Extension):
"""
Removes whitespace between HTML tags at compile time, including tab and newline characters.
It does not remove whitespace between jinja2 tags or variables. Neither does it remove whitespace between tags
and their text content.
Adapted from coffin:
https://github.com/coffin/coffin/blob/master/coffin/template/defaulttags.py
Adapted from StackOverflow:
https://stackoverflow.com/a/23741298/1090657
"""
2022-05-14 17:57:27 +00:00
tags = {"spaceless"}
2020-01-21 06:35:58 +00:00
def parse(self, parser):
lineno = next(parser.stream).lineno
2022-05-14 17:57:27 +00:00
body = parser.parse_statements(["name:endspaceless"], drop_needle=True)
2020-01-21 06:35:58 +00:00
return nodes.CallBlock(
2022-05-14 17:57:27 +00:00
self.call_method("_strip_spaces", [], [], None, None),
[],
[],
body,
2020-01-21 06:35:58 +00:00
).set_lineno(lineno)
def _strip_spaces(self, caller=None):
2022-05-14 17:57:27 +00:00
return Markup(re.sub(r">\s+<", "><", caller().unescape().strip()))