26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang でお手軽にテキストテンプレート処理をする

Posted at

漢なら golang で文字列テンプレート処理したいですね!

golang では text/template パッケージが標準で入っています.

でもサンプルを見ると構造体を作ってデータを流し込んでいてちょっと面倒ですね.

type Inventory struct {
	Material string
	Count    uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }

python のように dictionary 的にデータを流しこみたいですね.

できました.

package main

import (
    "fmt"
    "bytes"
    "text/template"
)

func main() {

    d := make(map[string]string)
    d["a"] = "muda"
    d["b"] = "dora"
    d["c"] = "bora"

    const t = "{{.a}} = {{.b}} + {{.c}}\n"
    tmpl, err := template.New("test").Parse(t)
    if err != nil {
        panic(err)
    }

    var doc bytes.Buffer
    if err := tmpl.Execute(&doc, d); err != nil {
        panic(err)
    }
    s := doc.String()

    fmt.Printf("Result: %s", s)
}
26
26
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?