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
Release: 2024-10-29 06:45:30
Original
781 people have browsed it

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

Inserting JSON:

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

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

In the template:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template