Course contentsShow
← Security
Lesson 1248 of 3,05225. Application Security - Secure CodingFree lesson

Safe vs Unsafe Template Functions

Identifying dangerous template functions that bypass auto-escaping and when their use is justified.

Safe vs Unsafe Template Functions

You'll learn how to distinguish between template functions that respect auto-escaping and those that dangerously bypass it.

The Core Problem

Most modern template engines automatically escape output to prevent injection attacks. However, they also provide special functions that bypass this protection—rendering content "as-is" without encoding. These unsafe functions exist for legitimate purposes, but they're a common source of vulnerabilities when misused.

Understanding the Distinction

Think of auto-escaping like a safety guard on power tools. Safe template functions work with the guard enabled—they assume input might be dangerous and encode it automatically. Unsafe functions are like disabling the guard: they tell the engine "trust me, I know what I'm doing" and insert content directly into the page.

Common unsafe function names include:

  • raw(), safe(), mark_safe() in various engines
  • |raw or |safe filters
  • Triple-brace syntax {{{variable}}} instead of {{variable}}

Safe functions:

  • Standard variable output {{variable}}
  • Built-in filters that maintain encoding

When Unsafe Functions Are Justified

Unsafe functions have legitimate uses:

  • Rendering pre-sanitized HTML from a trusted content management system
  • Inserting HTML generated by your own secure server-side code
  • Displaying content that's already been encoded in a different context

The golden rule: Only use unsafe functions when you have complete control over the content and have already validated/sanitized it at the application layer. Never use them directly with user input, even if you "think" it's safe.

Why This Matters

Using safe() on user-controlled data bypasses your last line of defense against XSS. It's the template equivalent of executing raw SQL instead of using parameterized queries.

Key Takeaway: Unsafe template functions bypass auto-escaping and should only be used with fully trusted, pre-sanitized content—never directly with user input.