Home  >  Article  >  Backend Development  >  How to Prevent HTML Escaping in GoLang Templates?

How to Prevent HTML Escaping in GoLang Templates?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 10:47:31987browse

How to Prevent HTML Escaping in GoLang Templates?

Inserting HTML into GoLang Templates

When populating HTML templates in GoLang, encountering issues with HTML characters being escaped and added incorrectly is not uncommon. To address this, it's crucial to understand the difference between passing data as a string and as template.HTML.

By default, GoLang templates will escape HTML characters when the data is passed as a string. This results in the unexpected output you described. To prevent this, the correct approach is to pass the HTML content as template.HTML. This data type is specifically designed to handle HTML content without escaping.

Here's an example of how to use template.HTML:

<code class="go">package main

import (
    "html/template"
    "os"
)

func main() {
    tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
    tplVars := map[string]interface{} {
        "Html": template.HTML("<p>Paragraph</p>"),
        "String": "<p>Paragraph</p>",
    }
    tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
}</code>

By passing the HTML content as template.HTML, the output will be rendered as intended, with HTML characters correctly displayed. This approach ensures that your HTML templates are populated accurately without any unwanted escaping.

The above is the detailed content of How to Prevent HTML Escaping in GoLang 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