使用 README 中的示例 golang gin 代碼:func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "foo": "bar", }) }}// in template index.tmpl<script>{{.foo}}</script>// result in html<script>"bar"</script>但是如果沒有引號我怎樣才能得到它,我只需要barvs "bar"?
1 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
模板包實現了 HTML 上下文感知引擎來提供注入安全的 html。
換句話說,它知道它在 script 標簽內執行,因此它不會輸出原始字符串,而是與 js 兼容的 json 編碼字符串。
要修復此問題,與評論建議的不同,請將字符串設置為template.JS
值,并且安全措施不會嘗試保護字符串。
參考 - https://golang.org/pkg/html/template/
包模板 (html/template) 實現數據驅動模板,用于生成安全的 HTML 輸出,防止代碼注入。
使用此類型會帶來安全風險:封裝的內容應來自受信任的來源,因為它將逐字包含在模板輸出中。
package main
import (
"html/template"
"os"
)
func main() {
c := `<script>
{{.foo}}
{{.oof}}
</script>`
d := map[string]interface{}{"foo": "bar", "oof": template.JS("rab")}
template.Must(template.New("").Parse(c)).Execute(os.Stdout, d)
}
https://play.golang.org/p/6qLnc9ALCeC
- 1 回答
- 0 關注
- 220 瀏覽
添加回答
舉報
0/150
提交
取消