8
9

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のTemplateで<select>タグを簡単に記述する

Last updated at Posted at 2014-12-18

Golangには標準でhtml/templateがありますが、Django formなどに慣れてると、物足りなさを感じます。
(私自身がDjangoに慣れてるわけじゃないですが・・)

ちょっと調べたらtemplateのFuncMap関数を使ったらテンプレート内で使える関数を簡単に定義できるようでしたのでやってみました。

http://play.golang.org/p/FshNbC3KsY

sample.go
package sample

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

func init() {
	http.HandleFunc("/", handle)
}

type tmplParams struct {
	Weekday *forHTMLSelect
	Month   *forHTMLSelect
}

type forHTMLSelect struct {
	Options  []string
	Selected int
}

func handle(w http.ResponseWriter, r *http.Request) {
	funcMap := template.FuncMap{
		"select": func(sel *forHTMLSelect) template.HTML {
			h := "<select>"
			for i, v := range sel.Options {
				var s string
				if i == sel.Selected {
					s = " selected"
				}
				h += fmt.Sprintf(`<option value="%d"%s>%s</option>`, i, s, v)
			}
			h += "</select>"
			return template.HTML(h)
		},
	}

	p := new(tmplParams)
	weekday := new(forHTMLSelect)
	weekday.Options = []string{"月曜", "火曜", "水曜"}
	weekday.Selected = 1
	p.Weekday = weekday

	const templateText = "<label>曜日:{{select .Weekday}}</label>"
	tmpl, _ := template.New("selectTest").Funcs(funcMap).Parse(templateText)
	tmpl.Execute(w, p)
}

出力
<label>曜日:<select><option value="0">月曜</option><option value="1" selected>火曜</option><option value="2">水曜</option></select></label>

forHTMLSelect型っていうのを自分で定義して、そこに選択肢とSelectedにしたい要素を入れます。
テンプレート内では{{ select . }}でoptionタグも全部書いてくれます。

標準以外のライブラリを使わないでもっと良い方法があったら教えて欲しいです。

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?