Home >Backend Development >Golang >How to safely replace newlines with `` in HTML templates?
In HTML templates, displaying newlines requires some consideration, as they can get escaped by the template to
, causing them to appear as literal HTML tags instead of line breaks. This poses a problem when loading a text file containing newlines and passing it to HTML templates.
The commonly proposed solution involves replacing the newline character (n) with
in the loaded string. However, this approach can lead to security vulnerabilities, as it allows attackers to inject malicious code through the " character in , evading XSS protection.
One alternative is to utilize template.HTMLEscape() to sanitize the text before performing the newline-to-
substitution. This method escapes potentially dangerous characters, ensuring the safety of the template data.
Here's an example demonstrating this technique:
<code class="go">import ( "html/template" "os" "strings" ) const page = `<!DOCTYPE html>\n<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>
When executed, the output will appear as:
<code class="html"><!DOCTYPE html> <html> <head> </head> <body> <p>first line<br><script>dangerous</script><br>last line</p> </body> </html></code>
In summary, passing sanitized text to HTML templates can effectively prevent XSS vulnerabilities while allowing for the correct display of newlines.
The above is the detailed content of How to safely replace newlines with `` in HTML templates?. For more information, please follow other related articles on the PHP Chinese website!