如何在gin gonic中不剝離HTML模板中的HTML註釋
P粉193307465
P粉193307465 2023-07-18 19:17:03
0
1
549

我正在使用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學習者快速成長!