HTML templates
Use `html/template` for server-rendered HTML, let autoescaping work, and keep template data explicit.
Canonical guidance
- use
html/templatefor HTML - rely on autoescaping by default
- pass explicit data to templates
Use when
- server-rendered pages
- email HTML generation with trusted boundaries
- embedded or filesystem-backed template sets
Avoid
text/templatefor HTML pages- concatenating raw HTML strings in handlers
- turning off safety with trusted types casually
Preferred pattern
- parse templates once, execute with a typed view-model value
Anti-pattern
- building HTML with
fmt.Sprintfand string concatenation
Explanation: This is tempting for small pages, but it drops escaping guarantees and quickly becomes unmaintainable.
Why
- HTML generation is a security boundary as much as a rendering concern
Related pages
Sources
- html/template package - Go Team
- embed package - Go Team