Home > Backend Development > Golang > How to Handle Newlines in HTML Templates Safely?

How to Handle Newlines in HTML Templates Safely?

Barbara Streisand
Release: 2024-11-03 20:59:02
Original
735 people have browsed it

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>
Copy after login

Output in Browser:

<code class="html">first line
<script>dangerous</script>
last line</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template