This solution has two drawbacks:
- It is too verbose. Typing "conditional_escape(...)" again and again is cumbersome.
from django import conditional_espace as esc
f'''
<h1>Hi {esc(name)}</h1>
Your messages: {esc(messages)}
'''
- If a conditional_escape() gets forgotten Cross-site scripting attacks could be possible, since malicious users could inject HTML.
This is specific to Django and other frameworks out there which accept anything as user input by default, that's an anti-pattern which OWASP recommends against because obviously it opens a wide range of attack vectors, absolutely no security audit would ever validate the default validation of a CharField or a TextField.
Another problem I see with this proposal is how do you actually use safe HTML in variables?
msgs = [f'<li>{msg}</li>' for msg in messages]
f'''
<h1>Hi {name}</h1>
Your messages: <ul>{msgs}</ul>
'''
Will output:
<h1>Hi Your name</h1>
Your messages: <ul><li>Your message</li></ul>
Instead of what we would want in this situation:
<h1>Hi Your name</h1>
Your messages: <ul><li>Your message</li></ul>
Otherwise good idea, it's an issue we have, even though the first immediate fix needed is Django's default input validation which is just openbar.