Home >Backend Development >Golang >How to Handle HTML and JSON Insertion in Go Templates Without Escaping Issues?

How to Handle HTML and JSON Insertion in Go Templates Without Escaping Issues?

DDD
DDDOriginal
2024-10-29 06:45:30758browse

How to Handle HTML and JSON Insertion in Go Templates Without Escaping Issues?

Handling HTML and JSON Insertion in Go Templates

Inserting HTML or JSON into Go templates can lead to escaping and other output formatting issues. To ensure the intended output, follow these guidelines:

Inserting HTML:

Use template.HTML instead of strings to prevent escaping. Example:

<code class="go">tplVars := map[string]interface{}{
    "Html": template.HTML("<p>Paragraph</p>"),
}</code>

Inserting JSON:

Pass JSON data as an interface{} value. Example:

<code class="go">type Data struct {
    Html  string
    Json  interface{}
}</code>

In the template:

<code class="go">{{.Data.Html}} {{.Data.Json}}</code>

Additional Notes:

  • Using template.HTML preserves HTML entities and ensures proper rendering.
  • Passing JSON data directly as an interface{} prevents unnecessary type conversion and automatic escaping.
  • Refer to the provided link for a runnable example: https://play.golang.org/p/QKKpQJ7gIs

The above is the detailed content of How to Handle HTML and JSON Insertion in Go Templates Without Escaping Issues?. 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