diff --git a/batiskaf/jinja2_ext/html_filters.py b/batiskaf/jinja2_ext/html_filters.py new file mode 100644 index 0000000..80e43f3 --- /dev/null +++ b/batiskaf/jinja2_ext/html_filters.py @@ -0,0 +1,33 @@ +from django.utils.text import normalize_newlines +import re +from django.utils.functional import allow_lazy +from django.utils.safestring import SafeData, SafeText, mark_safe +from django.utils.encoding import force_str, force_text +from django.utils import six + + +def escape(text): + """ + Returns the given text with ampersands, quotes and angle brackets encoded + for use in HTML. + This function always escapes its input, even if it's already escaped and + marked as such. This may result in double-escaping. If this is a concern, + use conditional_escape() instead. + """ + return mark_safe(force_text(text).replace( + '&', '&').replace('<', '<') + .replace('>', '>').replace( + '"', '"').replace("'", ''')) +escape = allow_lazy(escape, six.text_type, SafeText) + + +def linebreaks(value, autoescape=False): + """Converts newlines into

and
s.""" + value = normalize_newlines(value) + paras = re.split('\n{2,}', value) + if autoescape: + paras = ['

%s

' % + escape(p).replace('\n', '
') for p in paras] + else: + paras = ['

%s

' % p.replace('\n', '
') for p in paras] + return '\n\n'.join(paras)