如何在gin gonic中不剥离HTML模板中的HTML注释
P粉193307465
P粉193307465 2023-07-18 19:17:03
0
1
554

我正在使用Gin Gonic和一个HTML模板文件。

我的模板文件中包含类似于<!-- 这是我的注释 -->的(多行)HTML注释。我希望保留HTML内容在返回的输出中。

c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
    "name": "World",
})

问题:如何配置模板引擎或c.HTML以不剥离模板中的HTML注释?

更详细的回答

/static/templates/mytemplate.html:

<!DOCTYPE html>
<html lang="de">
<body>
<!--
这些行在输出中缺失。
-->
Hello World
</body>
</html>

我的处理程序:

func NewRouter() *gin.Engine {
    router := gin.Default()
    // ... load templates from file system ...
    router.GET("/foo", fooHandler)
    return router
}
func fooHandler(c *gin.Context) {
    c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
        "name": "World",
    })
}

编辑后,我尝试将注释添加为常量:

{{"<!-- my comment goes here -->"}}

但是标签被转义为

<!-- foo --> 


P粉193307465
P粉193307465

全部回复(1)
P粉237029457

我猜测HTML注释被删除的原因是因为我将HTML模板作为字符串读取(而不是直接作为文件读取)。仍然无法确定确切原因。不管怎样,对我有效的解决方法是在模板中使用占位符。

<!DOCTYPE html>
<html lang="de">
<body>
{{ .myComment }}
Hello World
</body>
</html>

并将HTML注释本身作为参数传递:

const myHtmlComment string = `
<!--
these lines are (not) missing (anymore) in the output
-->
`
func fooHandler(c *gin.Context) {
    c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
        "name": "World",
        "myComment": template.HTML(myHtmlComment),
    })
}

使用import "html/template"导入

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!