Home >Backend Development >Golang >How to Render Newlines Correctly in HTML Templates?
Overcoming the Escaping Issue in html/templates with Newlines
In HTML templates, newlines encoded as n are rendered as HTML entities (
) rather than actual line breaks. This occurs when the n characters are escaped by the template instead of accepted as part of trusted data.
Solution: Sanitization and Pre-Escaping
To resolve this issue, follow these steps:
Example Implementation:
The following code demonstrates the process:
<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)) }</code>
This code sanitizes the text, replaces newlines with
, and passes it to the template as pre-escaped data. The rendered result will correctly display line breaks as intended without escaping issues.
The above is the detailed content of How to Render Newlines Correctly in HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!