LoginSignup
0
0

More than 1 year has passed since last update.

Goのhtml/templateやGinでコメント文を削除させずに出力させたい時

Last updated at Posted at 2023-04-05

はじめに

よくあるWebサイトのhtmlを覗くとコメント文が書いてあることがよくあります。
ですが、Goで書いたWebサーバーはテンプレートを通すとコメント文がすべからく削除されます。

ブラウザ上では基本的に見ることは無いので高速化するのに助かる機能ですが....

他のWebサーバーで存在するのにGoには無いのが気持ち悪いのでコメントアウトを記述できるようにします(隠しAA書けないし

↓テンプレートに使うファイル

templates/index.html
<!DOCTYPE html>
<html>
    <head></head>
    <body>
    (適当な内容)
    {{"<!-- 適当なコメント -->" | safeHTML}}
    <!-- safeHTMLはgoで指定する任意の関数の名前 -->
    </body>
</html>

html/templateのみの場合

main.go
package main

import(
    "html/template"
    "log"
	"net/http"
)

func main() {
    // ハンドラを指定
    http.HandleFunc("/", TopPage)
    // 80番ポートで鯖立て
    log.Fatal(http.ListenAndServe(":80", nil))
}

// index.htmlのハンドラ関数
func TopPage(w http.ResponseWriter, r *http.Request){
    fileDir := "templates/"        // htmlのディレクトリ
    fileName := "index.html"  // ファイル名
    data := nil // テンプレートに渡す構造体

    // テンプレートで使用する関数マップ
	funcMap := template.FuncMap{
        // ここでテンプレートの関数に文字列を生のhtmlとして描画する関数を登録する(名前は任意でよい)
		"safeHTML": func(text string) template.HTML { return template.HTML(text) },
	}

    // テンプレートを描画
    t := template.Must(template.New(fileName).Funcs(funcMap).ParseFiles(fileDir + fileName))
	if err := t.Execute(w, data); err != nil {
    	log.Println(err)
	}

}

Ginを使った場合

自分はginを使った方が楽です

main.go
package main

import(
    "html/template"
    "log"
	"net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    
    router := gin.Default()

    // ここでテンプレートの関数に文字列を生のhtmlとして描画する関数を登録する(名前は任意でよい)
    // routerで指定するハンドラ全部に反映されるので良き
    router.FuncMap["safeHTML"] = func(text string) template.HTML { return template.HTML(text) }

    // ファイルを事前にロード
	router.LoadHTMLGlob("templates/*")

    // ハンドラを指定
    router.GET("/",TopPage)

    // 80番ポートで鯖立て
    log.Fatal(http.ListenAndServe(":80", router))
}

// index.htmlのハンドラ関数
func TopPage(c *gin.Context){
	c.HTML(http.StatusOK, "index.html", nil)
}

結果

こんな感じの出力になります

<!DOCTYPE html>
<html>
    <head></head>
    <body>
    (適当な内容)
    <!-- 適当なコメント -->
    </body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0