2

Gin 无法解析 HTML 模板

 2 years ago
source link: https://peon.top/show/2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Gin 无法解析 HTML 模板蜂鸟的小窝
Gin 无法解析 HTML 模板

    问题发生在有一天晚上,我读到了某个富文本编辑器编辑的文章,但发现 Golang 默认会将HTML原样输出。于是我苦苦的寻求方法,直到我发现了 template.HTML 这个方法。

原来想要输出像PHP Laravel 那样 {!! !!} 不转义 HTML 的方法是,先将 String 类型转换为 template.HTML 类型,再输出到模板里就好了。';">';">';">';">';">';font-size:9.8pt;">

于是我做了我先定义了一个函数在我的程序上

func Unescaped(str string) template.HTML {
	return template.HTML(str)
}

再在 Gin 启动时注册这个函数

gin.Engine.SetFuncMap(template.FuncMap{"Unescaped": helpers.Unescaped})

这句话一定要放在 LoadHTMLGlob 前,否则将不起作用

此时模板里就可以直接调用 Unsecaped 函数了

{{ .Article.Content | Unescaped }}

至此问题圆满解决


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK