在做一些文章详情页的时候,因为用到了富文本编辑器,因此数据库中存储的是HTML格式的内容,当从数据库中读取显示到页面时需要进行转换,否则显示就是实际的字符串内容,因此需要进行转换,转换的代码很简单,就是通过关键函数template.HTML
示例如下:
"content": template.HTML(a.Content),
另外可以自定义模板函数,在模板文件中使用:
package main
import (
"html/template"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
router.LoadHTMLFiles("./index.tmpl")
router.GET("/index", func(c *gin.Context) {
c.HTML(200, "index.tmpl", "<a href='lizhouwen.com'>1232</a>")
})
router.Run(":9999")
}
html代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>bert</title>
</head>
<body>
<h1>2134</h1>
<div>{{ . | safe }}</div>
</body>
</html>
0 Comments