html package provides functions for escaping and unescaping HTML text, and the html/template subpackage provides data-driven templates for generating HTML output safe against code injection.
html Package
HTML Escaping
html/template Package
Provides data-driven templates with automatic contextual escaping.Basic Template
Template from File
Multiple Templates
Template Syntax
Variables
Conditionals
Loops
With
Variables
Template Inclusion
Define and Block
Template Functions
Built-in Functions
Custom Functions
Practical Examples
Web Page Template
Email Template
HTML Form with Validation
Template Caching
Security Features
Automatic Escaping
Safe HTML
URL Escaping
Best Practices
- Use template caching - Parse templates once, reuse many times
- Validate data before rendering - Don’t rely solely on template escaping
- Use typed data structures - Avoid
map[string]interface{} - Handle errors - Check template execution errors
- Organize templates - Use subdirectories and naming conventions
- Use Must carefully - Only for templates that must parse successfully
- Be careful with HTML/JS/CSS - Use appropriate safe types
- Test templates - Write tests for template rendering