Home >Backend Development >Golang >How to Properly Render Line Breaks in HTML Templates?

How to Properly Render Line Breaks in HTML Templates?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 14:59:02983browse

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:

  1. Sanitize the input: Use the template.HTMLEscape() function to sanitize the text and remove any potentially malicious fragments.
  2. Substitute newlines: After sanitization, substitute the newlines (n) with markup (
    ).
  3. Wrap in HTML: Encapsulate the preprocessed text as HTML using template.HTML. This ensures that the template engine knows the content is safe.
  4. Execute the template: Pass the sanitized and preprocessed text to the template for rendering.

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!

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