Home > Article > Backend Development > How to Handle Newlines in HTML Templates Safely?
Escaping Newlines in HTML Templates
When loading a text file with newlines into HTML templates, it's essential to take precautions against cross-site scripting (XSS) attacks. Ideally, n characters should be replaced with
tags to preserve line breaks in the browser. However, directly substituting the characters may result in the template escaping them as HTML entities
, which won't render as intended.
Solution Using template.HTMLEscape()
To avoid the issue while maintaining XSS protection, consider using the template.HTMLEscape() function first to sanitize the text. This function escapes dangerous characters before substituting n with
.
Example:
<code class="go">package main import ( "html/template" "os" "strings" ) const page = `<!DOCTYPE html> <html> <head> </head> <body> <p>{{.}}</p> </body> </html>` const text = `first line <script>dangerous</script> last line` func main() { t := template.Must(template.New("page").Parse(page)) safe := template.HTMLEscapeString(text) safe = strings.Replace(safe, "\n", "<br>", -1) t.Execute(os.Stdout, template.HTML(safe)) // template.HTML encapsulates a known safe HTML document fragment. }</code>
Output in Browser:
<code class="html">first line <script>dangerous</script> last line</code>
By escaping the text before substitution, the template correctly renders line breaks while protecting against XSS attacks.
The above is the detailed content of How to Handle Newlines in HTML Templates Safely?. For more information, please follow other related articles on the PHP Chinese website!