Skip to content

Instantly share code, notes, and snippets.

@tokubass
Last active July 12, 2016 12:12
Show Gist options
  • Save tokubass/4d5699d364d5fe5937d91c499af4448f to your computer and use it in GitHub Desktop.
Save tokubass/4d5699d364d5fe5937d91c499af4448f to your computer and use it in GitHub Desktop.

Text and HTML Templates

actionと呼ばれるdouble brace {{ }}

  • 構造体フィールド選択
  • 関数呼び出し
  • メソッド呼び出し
  • 制御構文(if-eles)
  • range loop

前章のgithub.IssuesSearchResult構造体を使用した例

const templ = `{{.TotalCount}} issues: 
{{range .Items}}----------------------------------------
 Number: {{.Number}}
 User: {{.User.Login}
 Title: {{.Title | printf "%.64s" ]}
 Age: {{.CreatedAt | daysAgo}} days
 {{end}}`

dotは現在の値を参照する

  • .TotalCount -> IssuesSearchResult.TotalCount
  • .Items -> IssuesSearchResult.Items
  • .Number-> range loopで取り出されているItemsの要素

| はsellのpipeのようなもの

結果を関数に渡せる

  • printf templateの中で使えるfmt.Sprintfのsynonym

  • daysAgo time.Timeを変換するオリジナル関数

func daysAgo(t time.Time) int {
	return int(time.Since(t).Hours() / 24)
}

型ごとにjsonの[un]marshalを定義

http://qiita.com/taizo/items/2c3a338f1aeea86ce9e2 daysAgoを作らなくても独自フォーマットでoutputできる

テンプレートは2ステップ

  • テンプレートファイルをパースして、内部表現に変換
  • 値の入力して最終結果を得る

テンプレートファイルのパースはコンパイル時に1度だけ

report, err := template.New("report").
		// template.FuncMapでオリジナル関数をテンプレートから呼び出せるように登録
		Funcs(template.FuncMap{"daysAgo": daysAgo }).
		Parse(templ)

if err != nil {
	log.Fatal(err)
}
// template.Mustというエラーハンドリングを便利にしてくれるものがある。templateが不正な場合panicを起こす。
var report = template.Must(template.New("issuelist").
	Funcs(template.FuncMap{"daysAgo": daysAgo}).
	Parse(templ))

func main() {
	result, err := github.SearchIssues(os.Args[1:])
	if err != nil {
		log.Fatal(err)
	}
	// 最終的な成果物を得るためにExecuteの引数には出力先と、データソースを与える。
	if err := report.Execute(os.Stdout, result); err != nil {
		log.Fatal(err)
	}
}

オートエスケープ

  • html/templateパッケージはtext/templateパッケージと類似したAPI、式をもつが、コンテキスト(html,js,css,url)別のオートエスケープ機能がある。
  • まちがえてtext/templateを使うと、テンプレートパラメータに<,> が含まれているとHTMLが壊れる

明示的にオートエスケープ抑制

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment