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

How to Display Newlines Correctly in HTML Templates?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 12:38:01939browse

How to Display Newlines Correctly in HTML Templates?

Displaying Newlines Correctly in HTML Templates

When loading text files with newlines into HTML templates, developers often encounter an issue where these newlines are escaped to "
" instead of being displayed as line breaks. This can be problematic for maintaining correct formatting and readability.

To address this challenge, you can first sanitize your text using template.HTMLEscape() to remove any potential XSS vulnerabilities. Subsequently, you can replace the newlines ("n") with "
" using strings.Replace(). The modified text should then be encapsulated within template.HTML() to mark it as a trusted and safe HTML fragment.

An example implementation in Go demonstrates this approach:

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

This approach ensures that the newlines are displayed correctly as line breaks in the browser, while maintaining the integrity of the rendered HTML content.

The above is the detailed content of How to Display 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