How to Render Newlines Correctly in HTML Templates?

Susan Sarandon
Release: 2024-10-30 20:02:02
Original
696 people have browsed it

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!