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?
/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 -->
我猜測(cè)HTML注釋被刪除的原因是因?yàn)槲覍TML模板作為字符串讀?。ǘ皇侵苯幼鳛槲募x?。?。仍然無(wú)法確定確切原因。不管怎樣,對(duì)我有效的解決方法是在模板中使用占位符。
<!DOCTYPE html> <html lang="de"> <body> {{ .myComment }} Hello World </body> </html>
并將HTML注釋本身作為參數(shù)傳遞:
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"導(dǎo)入