0

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>&amp;</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.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • 1
    Negative lookarounds to make sure there's only a single brace? But you're packing quite a lot of anti-patterns into one function here, there are quite a few existing templating systems you could use. – jonrsharpe Mar 27 '21 at 22:11
  • @jonrsharpe please tell me template system which support Django's SafeString and which gives me roughly something like this above. The Django template language hides errors which I don't want in this current context. – guettli Mar 27 '21 at 22:19
  • @jonrsharpe anti-patterns .... Is f-string-formatting an anti-pattern? – guettli Mar 27 '21 at 22:22
  • 1
    You mean using f-strings generally? No, obviously not, but also how would that be relevant given you're *not* using them? – jonrsharpe Mar 27 '21 at 22:24
  • 2
    f-strings work with special compiler support by re-writing the code into the equivalent `.format` call. Using `eval` is an entirely different kettle of fish, as is inspecting the stack to get at the caller's locals. – Karl Knechtel Mar 27 '21 at 22:28
  • @KarlKnechtel thank you for this hint. Is it possible to implement the f-string magic, too? I created a follow-up question: https://stackoverflow.com/questions/66839921/implement-f-string-like-magic-to-pimp-djangos-format-html – guettli Mar 28 '21 at 09:18

0 Answers0