Wie man HTML-Kommentare in der HTML-Vorlage in Gin Gonic nicht entfernt
P粉193307465
P粉193307465 2023-07-18 19:17:03
0
1
553

Ich verwende Gin Gonic und eine HTML-Vorlagendatei.

Meine Vorlagendatei enthält (mehrzeilige) HTML-Kommentare ähnlich wie <!--Das ist mein Kommentar -->. Ich möchte den HTML-Inhalt in der zurückgegebenen Ausgabe beibehalten.

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

Frage: Wie konfiguriere ich die Template-Engine oder c.HTML so, dass HTML-Kommentare in Vorlagen nicht entfernt werden?

Detailliertere Antwort

/static/templates/mytemplate.html:

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

Mein Betreuer:

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",
    })
}

Nach der Bearbeitung habe ich versucht, die Anmerkung als Konstante hinzuzufügen :

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

aber das Tag wird als

maskiert
<!-- foo --> 


P粉193307465
P粉193307465

Antworte allen(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"导入

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!