Home >Backend Development >Golang >How to Render Newlines Correctly in HTML Templates?

How to Render Newlines Correctly in HTML Templates?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 20:02:02745browse

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:

  1. Sanitize the text: Use template.HTMLEscape() to remove any potentially harmful characters from the text file.
  2. Substitute newlines: After sanitization, replace all occurrences of "n" with "
    ".
  3. Use pre-escaped data: Pass the sanitized and substituted text to the template as template.HTML, which encapsulates safe HTML fragments.

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!

Statement:
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