Home > Backend Development > Golang > Why Does 'ZgotmplZ' Appear in My Go HTML Templates, and How Can I Fix It?

Why Does 'ZgotmplZ' Appear in My Go HTML Templates, and How Can I Fix It?

Linda Hamilton
Release: 2024-12-16 05:44:09
Original
697 people have browsed it

Why Does

Resolving "ZgotmplZ" Output in Go HTML Templates

When a Go template function outputs HTML, the unexpected appearance of "ZgotmplZ" may arise. This peculiar value indicates the presence of unsafe content within a CSS or URL context during runtime.

Cause and Solution

"ZgotmplZ" signifies that raw, potentially dangerous data has erroneously entered a CSS or URL context. To remedy this, the safe and attr functions must be added to the template's funcMap. These functions convert the data to safe HTML and HTML attributes, respectively.

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := template.FuncMap{
        "attr": func(s string) template.HTMLAttr {
            return template.HTMLAttr(s)
        },
        "safe": func(s string) template.HTML {
            return template.HTML(s)
        },
    }

    template.Must(template.New("Template").Funcs(funcMap).Parse(`
    <option {{.attr | attr}}>>test</option>
        {{.html | safe}}
     `)).Execute(os.Stdout, map[string]string{
        "attr": `selected=&quot;selected&quot;`,
        "html": `<option selected=&quot;selected&quot;>test</option>`,
    })
}
Copy after login

Output

This corrected code will generate the desired output:

<option selected=&quot;selected&quot;>test</option>
<option selected=&quot;selected&quot;>test</option>
Copy after login

Customization

Developers may opt to define additional functions that can convert strings to other HTML-safe types such as template.CSS, template.JS, template.JSStr, and template.URL.

The above is the detailed content of Why Does 'ZgotmplZ' Appear in My Go HTML Templates, and How Can I Fix It?. 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