I implemented a fun little method h()
which is Django's format_html() on steroids:
It works fine, except the last assert fails, and I am unsure how to implement it:
def test_h():
amp = '&'
assert h('{amp}') == '&'
foo = format_html('<span>{bar}</span>', bar='&')
assert h('<div>{foo}</div>') == '<div><span>&</span></div>'
assert h('{') == '{'
assert h('') == ''
name='foo'
assert h('{name.upper()}') == 'FOO'
assert h('{{}}') == '{}' # <--------------- how to get this working?
Implementation:
def h(html):
"""
Django's format_html() on steroids
"""
def replacer(match):
call_frame = sys._getframe(3)
return conditional_escape(
eval(match.group(1), call_frame.f_globals, call_frame.f_locals))
return mark_safe(re.sub(r'{(.*?)}', replacer, html))
How to implement the method, so that {{
and }}
get ignored?
BTW: further ideas to extensions are welcome. Maybe I will create a python package later.