gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:14 27 4
gpt4 key购买 nike

当我将参数传递给 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com