LoginSignup
4
4

More than 5 years have passed since last update.

html/templateで自作の関数を利用する

Last updated at Posted at 2017-05-19

はじめに

html/template で日付を表示してみた。

<div>{{.Date.Month}}月{{.Date.Day}}日</div>

ブラウザで見てみると

May月18日

メイ!!!!

goのコードならば int(Date.Month()) としてあげれば数字に変換されるのだけど、テンプレートでキャストする方法がわからなかったので自作の関数をテンプレートで使えるようにしてみました。そしたら結構ハマりました。

自作の関数を利用する方法

まず正解を書いてしまいます。こんなコードで自作した month2int() をテンプレートから呼び出せます。

hoge.go
func month2int(m time.Month) int {
    return int(m)
}

func handler(w http.ResponseWriter, r *http.Request) {
    type Param struct {
        Date    time.Time
    }
    param := Param{Date:time.Now()}

    files := []string{"template/index.html"}
    tname := filepath.Base(files[0])
    f := template.FuncMap{
        "month2int": month2int,
    }
    tpl, _ := template.New(tname).Funcs(f).ParseFiles(files...)
    if err := tpl.Execute(w, param); err != nil {
        log.Println(err)
    }
}
index.html
<div class="date">{{.Date.Month | month2int}}月{{.Date.Day}}日</div>

template.ParseFiles() でテンプレートファイルを読み込むと思いますが、関数を登録するには template.New() を使う必要があります。かつ New() の引数には最初のファイルパスのファイル名だけを与える必要があります。それをしないと、、、

template: "" is an incomplete or empty template

というエラーが出てしまいます。

おしまい。

参考にした記事

template Funcs and ParseFiles

4
4
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
4
4