为什么我在Go HTML模板输出中看到ZgotmplZ? [英] Why am I seeing ZgotmplZ in my Go HTML template output?

查看:1072
本文介绍了为什么我在Go HTML模板输出中看到ZgotmplZ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用Go模板函数输出HTML时,它显示 ZgotmplZ

When I'm calling a Go template function to output HTML, it displays ZgotmplZ.

示例代码:

http://play.golang.org/p/tfuJa_pFkm

http://play.golang.org/p/tfuJa_pFkm

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := template.FuncMap{
        "printSelected": func(s string) string {
            if s == "test" {
                return `selected="selected"`
            }
            return ""
        },

        "safe": func(s string) template.HTML {
            return template.HTML(s)
        },
    }
    template.Must(template.New("Template").Funcs(funcMap).Parse(`
    <option {{ printSelected "test" }} {{ printSelected "test" | safe }} >test</option>
    `)).Execute(os.Stdout, nil)

}

输出:

<option ZgotmplZ ZgotmplZ >test</option>


推荐答案

ZgotmplZ是一个特殊值,表示不安全内容在运行时达到
CSS或URL上下文。这个例子的输出是:

"ZgotmplZ" is a special value that indicates that unsafe content reached a CSS or URL context at runtime. The output of the example will be:

 <img src="#ZgotmplZ">

您可以在模板funcMap中添加一个安全和attr函数:

You can add a safe and attr function to the template funcMap:

package main

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="selected"`,"html":`<option selected="selected">option</option>`})
}

输出将如下所示:

The output will look like:

<option selected="selected" >test</option>
<option selected="selected">option</option>

您可能想要定义一些其他函数,可以将字符串转换为template.CSS,template.JS, template.JSStr,template.URL等。

You may want to define some other functions which can convert string to template.CSS, template.JS, template.JSStr, template.URL etc.

这篇关于为什么我在Go HTML模板输出中看到ZgotmplZ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆