覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

Go言語 - HTMLテンプレートの使い方

GolangでのHTMLテンプレート記述方法や値の展開方法等について学ぶために、html/templateを試してみました。


変数をそのまま展開

コード内の変数をhtmlのテンプレートに展開する例です

■htmlテンプレート(template000.html.tpl)

<!DOCTYPE html>
<html>
<body>
    msg: {{.}} 
</body>
</html>

■サンプルコード

package trial

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

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

    str := "Sample Message"

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template000.html.tpl", str); err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/page0", htmlHandler0)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144443p:plain


mapの値を展開

mapをhtmlのテンプレートに展開する例です

■htmlテンプレート(template001.html.tpl)

<!DOCTYPE html>
<html>
<body>
    key1: {{.key1}}, key2: {{.key2}}, key3: {{.key3}} 
</body>
</html>

■サンプルコード

package trial

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

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

    m := map[string]int{
        "key1": 101,
        "key2": 202,
        "key3": 303,
        "key4": -404,
    }

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template001.html.tpl", m); err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/page1", htmlHandler1)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144531p:plain


構造体を展開

構造体をhtmlのテンプレートに展開する例です

■htmlテンプレート(template002.html.tpl)

<!DOCTYPE html>
<html>
<body>
    Name: {{ .Name }}, Age: {{ .Age }} 
</body>
</html>

■サンプルコード

package trial

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

func htmlHandler2(w http.ResponseWriter, r *http.Request) {

    t := template.Must(template.ParseFiles("templates/template002.html.tpl"))

    type SampleData struct {
        Name string
        Age  int
    }

    data := SampleData{Name: "Taro", Age: 25}

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template002.html.tpl", data); err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/page2", htmlHandler2)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144541p:plain


関数を実行

htmlのテンプレート内で関数呼び出しを行う例です

■htmlテンプレート(template003.html.tpl)

<!DOCTYPE html>
<html>
<body>
    Func1 -> {{ samplefunc1 }}
<br/>
    Func2 -> {{.msg1 | samplefunc2}}
<br/>
    Func3 -> {{.msg2 | samplefunc3}}
</body>
</html>

■サンプルコード

package trial

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

func htmlHandler3(w http.ResponseWriter, r *http.Request) {

    funcMap := template.FuncMap{
        "samplefunc1": func() string { return time.Now().String() },
        "samplefunc2": func(src string) string { return fmt.Sprintf("[$$ %s $$]", src) },
        "samplefunc3": strings.ToUpper,
    }
    // テンプレートをパース
    t := template.Must(template.New("t").Funcs(funcMap).ParseFiles("templates/template003.html.tpl"))

    m := map[string]string{
        "msg1": "golang is programming language.",
        "msg2": "hello template app.",
    }

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template003.html.tpl", m); err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/page3", htmlHandler3)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144551p:plain


ループ

htmlのテンプレート内でループを行う例です

■htmlテンプレート(template004.html.tpl)

<!DOCTYPE html>
<html>
<body>
    <div>
        <h4>DataList</h4>
        {{range .}}
        <p>{{.}}</p>
        {{end}}
    </div>
</body>
</html>

■サンプルコード

package trial

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

func htmlHandler4(w http.ResponseWriter, r *http.Request) {

    t := template.Must(template.ParseFiles("templates/template004.html.tpl"))

    strArray := []string{"aa", "bbb", "ccc", "dddd"}

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template004.html.tpl", strArray); err != nil {
        log.Fatal(err)
    }
}

func main() {
    http.HandleFunc("/page4", htmlHandler4)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144607p:plain


リクエストパラメータをテンプレートにセットして表示

htmlのテンプレート内で受け取ったリクエストパラメータを反映する例です

■htmlテンプレート(template005.html.tpl)

<!DOCTYPE html>
<html>
<body>
<div>
  Request Param1 -> {{.Param1 |safehtml}}
</div>
<div>
  Request Param2 -> {{.Param2 |safehtml}}
</div>
</body>
</html>

■サンプルコード

package trial

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

func htmlHandler5(w http.ResponseWriter, r *http.Request) {
    funcMap := template.FuncMap{
        "safehtml": func(text string) template.HTML { return template.HTML(text) },
    }
    t := template.Must(template.New("T").Funcs(funcMap).ParseFiles("templates/template005.html.tpl"))

    st := struct {
        Param1 string
        Param2 string
    }{
        Param1: r.FormValue("param1"),
        Param2: r.FormValue("param2"),
    }

    // テンプレートを描画
    if err := t.ExecuteTemplate(w, "template005.html.tpl", st); err != nil {
        log.Fatal(err)
    }
}

func LoadTemplate() {
    http.HandleFunc("/page5", htmlHandler5)

    // サーバーを起動
    http.ListenAndServe(":8989", nil)
}


■ブラウザでのアクセス結果

f:id:nini_y:20170702144616p:plain



関連エントリ