LoginSignup
22
21

More than 5 years have passed since last update.

Golangのテンプレート(Template)を使ってみる

Last updated at Posted at 2018-07-28

Golang標準で使えるTemplateを使ってみます。
Templateを使用するとプログラムとデザインを分離することができます。

では、実際にやってみましょう。
下記のようにプログラム(server.go)とテンプレート(clock.tpl)を用意します。

server.go
package main

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

func main() {
    // /now にアクセスした際に処理するハンドラーを登録
    http.HandleFunc("/now", handleClockTpl)

    // サーバーをポート8080で起動
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleClockTpl(w http.ResponseWriter, r *http.Request) {
    // テンプレートをパース
    tpl := template.Must(template.ParseFiles("clock.tpl"))

    m := map[string]string{
        "Date": time.Now().Format("2006-01-02"),
        "Time": time.Now().Format("15:04:05"),
    }

    // テンプレートを描画
    tpl.Execute(w, m)
}
clock.tpl
<!DOCTYPE html>
<html><body>
    <p>Date={{.Date}}</p>
    <p>Time={{.Time}}</p>
</body></html>

そして実行して、アクセスするとこんな感じです。

テンプレートテスト.png

{{.date}}{{.time}} がmapの要素に置き換わっているのが分かると思います。
ちなみに下記のようにmapではなく、構造体も使えます。

server.go(構造体の例
package main

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

func main() {
    // /now にアクセスした際に処理するハンドラーを登録
    http.HandleFunc("/now", handleClockTpl)

    // サーバーをポート8080で起動
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleClockTpl(w http.ResponseWriter, r *http.Request) {
    // テンプレートをパース
    tpl := template.Must(template.ParseFiles("clock.tpl"))

    type DateTime struct {
        Date string
        Time string
    }

    now := DateTime{Date: time.Now().Format("2006-01-02"), Time: time.Now().Format("15:04:05")}

    // テンプレートを描画
    tpl.Execute(w, now)
}

やはりデザイン部分は別ファイルにしたほうが、プログラムが見やすく、管理もしやすくなります。
数行のプログラムだとピンとこないかもしれませんが(笑)

それと、標準のTemplateでは対応していない、テンプレートファイルから別のテンプレートファイルをインクルードするような使い方をしたかったので、ちょっと独自にテンプレートエンジンを作ってみました。
興味のある方は下記からどうぞ。
Golangのインクルード(include)対応テンプレート(goingtpl)を作ってみた

22
21
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
22
21