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

How to Properly Render Line Breaks in HTML Templates?

Linda Hamilton
Release: 2024-10-30 14:59:02
Original
986 people have browsed it

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

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!

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