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

示例代码:

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>

推荐答案

"ZgormplZ"是一个特定值,表示不安全内容已到达 运行时的CSS或URL上下文.该示例的输出将为:

 <img src="#ZgotmplZ">

您可以向模板funcMap添加一个SAFE和ATTR函数:

程序包主干

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>`})
}

输出将如下所示:

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

您可能需要定义一些其他函数来将字符串转换为template.CSS、template.JS、template.JSStr、template.URL等.

Go相关问答推荐

如何预编译Golang标准库?

如何确定泛型类型在运行时是否可比较?

如何使用 html/template 在 golang 中运行一个范围内的范围

在多个 struct 体中重用 Go 中的函数

用接口来模拟amqp091go的困难

Caddy服务器try 打开端口80而不是8090.

Golang prometheus:有没有办法衡量出站请求的指标?

无法从主域访问子域:无Access-Control-Allow-Origin

在本地 go 应用程序上获取秘密的正确策略

我突然无法再将我的 GoLang 应用程序部署到 Google AppEngine

如何使用 Go 代理状态为 OK 的预检请求?

在 Go 模板中对照片使用随机 Int

通过环境变量配置 OTLP 导出器

此代码如何生成内存对齐切片?

如何在 GORM 中迭代一个 int 数组

即使一个测试用例失败,如何运行所有测试用例

Go 中 SDL Surface 的 OpenGL 纹理

出于某种原因,Golang (Go) AES CBC 密文被填充了 16 个 0x00 字节

具有多个嵌入式 struct 的 Go MarshalJSON 行为

如何动态解析 Go Fiber 中的请求正文?