Home >Backend Development >Golang >How to Properly Render Line Breaks in HTML Templates?
Replacing Newlines with
in HTML Templates
In HTML templates, replacing newlines (n) with markup (
) can lead to unexpected behavior due to escaping. When the loaded string is passed to the template, newlines are escaped to
, resulting in their display as literal text instead of line breaks.
Solution:
To address this issue, you can preprocess the text prior to using it in the template. Here's how:
Example Code:
<code class="go">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)) // Encapsulate as HTML }</code>
This code ensures that any malicious content in the input text is neutralized and allows for proper rendering of newlines using markup.
The above is the detailed content of How to Properly Render Line Breaks in HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!