Performance: XSS prevention in templates
This affects page security and rendering speed by controlling how user input is handled and displayed in templates.
Jump into concepts and practice - no test required
{{ user_input }}{% autoescape off %}{{ user_input }}{% endautoescape %}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Autoescape enabled (default) | Minimal, safe DOM nodes | 0 reflows from scripts | Normal paint cost | [OK] Good |
| Autoescape disabled with raw input | Potentially many DOM changes from scripts | Multiple reflows possible | High paint cost due to layout shifts | [X] Bad |
| Using |safe filter on untrusted input | Uncontrolled DOM manipulations | Multiple reflows and repaints | High paint cost and CLS risk | [X] Bad |
| Explicit escaping with |escape filter | Safe DOM nodes | 0 reflows from scripts | Normal paint cost | [OK] Good |
safe filter tells Django not to escape the variable, rendering HTML as-is.escape escapes content, strip and clean are not standard Django filters for safety.{{ user_input }}<script>alert('XSS')</script>, what will be rendered in the browser?{{ comment|safe }}safe on user input disables escaping, allowing scripts to run if input is malicious.safe to untrusted input is unsafe and causes XSS vulnerabilities.safe filter is used on untrusted user input. [OK]<b> and <i>, but prevent scripts. Which approach best prevents XSS while allowing these tags?{{ comment|safe }} directly risks XSS by trusting raw input; combining |escape and |safe misuses filters; disallowing all HTML prevents desired formatting.{{ comment|safe }}. [OK]