go - 通过 html/template 删除传递参数周围的空格

标签 go

当我将参数传递给 onclick 函数时,我在该参数周围有空格,为什么以及如何删除它们?

t, _ := template.New("").Parse(`<div onclick="test({{.}})">{{.}}</div>`)
t.Execute(os.Stdout, 1)

结果:

<div onclick="test( 1 )">1</div>

playground

编辑:

由 Dave 帮助更新,从模板我们可以做这样的事情:

t, _ := template.New("").Funcs(template.FuncMap{
    "test": func(i interface{}) template.JS {
        switch i.(type) {
        case int:
            s := strconv.Itoa(i.(int))
            return template.JS(s)   
        // other types
        default:
            panic("bad type")
        }
    },
}).Parse(`<div onclick="test({{test .}})">{{.}}</div>`)
t.Execute(os.Stdout, 1)

playground

最佳答案

这是 Golang 采取一些措施以确保恶意 JS 不会最终出现在您的模板中的结果。如果您指定您传入的内容对于 javascript 是安全的,它将正常工作。

type JS

Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

https://play.golang.org/p/TUOECg1YDtl

t.Execute(os.Stdout, template.JS("1"))

结果:

<div onclick="test(1)">1</div>

关于go - 通过 html/template 删除传递参数周围的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54961482/

相关文章:

go - 垃圾收集器和延迟函数之间的冲突?

去 channel 和死锁

go - 使用go-tdlib停留在“authorizationsStateWaitPhoneNumber”状态

arrays - 理解 Go 的 slice 符号

arrays - 使用 pgx 使用 JSONBArray 时出现 "wrong element type"

go - 动态命名字段名称

go - 无法将 interface{} 直接转换为 []map[string]interface{}

Golang 打印 "nil"

sql - Golang 在 postgres 中包装查询执行

go - 解释: Don't communicate by sharing memory; share memory by communicating