4
4

More than 5 years have passed since last update.

Goのテンプレートでカスタム関数を定義するメモ

Posted at

ただのメモだ。

template.go
package main

import (
    "fmt"
    "os"
    "text/template"
    "time"
)

func isotime(layout string) string {
    now := time.Now()
    return now.Format(layout)
}

func timestamp() string {
    return time.Now().Format("20060102030405")
}

func main() {
    tmplText1 := "Path is: /path/to/{{isotime `20060102030405`}}\n"
    tmplText2 := "Path is: /path/to/{{timestamp}}\n"

    funcMap := template.FuncMap{
        "isotime":   isotime,
        "timestamp": timestamp,
    }

    t1, err := template.New("isotime").Funcs(funcMap).Parse(tmplText1)
    if err != nil {
        fmt.Printf("execution: %s", err)
    }
    err = t1.Execute(os.Stdout, "")
    if err != nil {
        fmt.Printf("execution: %s", err)
    }

    t2, err := template.New("timestamp").Funcs(funcMap).Parse(tmplText2)
    if err != nil {
        fmt.Printf("execution: %s", err)
    }
    err = t2.Execute(os.Stdout, "")
    if err != nil {
        fmt.Printf("execution: %s", err)
    }
}
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