2020-01-21 06:35:58 +00:00
|
|
|
import re
|
|
|
|
|
|
|
|
from jinja2 import Markup, nodes
|
|
|
|
from jinja2.ext import Extension
|
|
|
|
|
|
|
|
|
|
|
|
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()))
|