LoginSignup
2
2

More than 5 years have passed since last update.

RevelのTemplateで時間の分を扱う

Last updated at Posted at 2015-07-30

DBで時間の分をintで保持している想定で、値の処理を考える
Formの値をintで持つと、FlashはStringで値を返すのでwith fieldは使わずoptionタグを普通に書く必要がある

type Time struct {
    Hour int
    Min  int
}
time := Time{}
time.Min = 10
mins := []int{0,5,10,15,20,25,30,35,40,45,50,55}
<select name="time.Min">
{{range $index,$element := .mins}}
  <option value="{{$element}}" {{if eq $element $min}}selected{{end}}>{{$element}}分</option>
{{end}}
</select>

Flashした時はstringで返ってきた値をintに戻す必要がある
time.Min, _ = strconv.Atoi(c.Flash.Data["time.Min"])

別の提案

Flashの処理が必要。。FORMでは最初からStringで扱う用の構造体を用意するのはどうか?
そうすればwithでFiledを扱うこともできるはず。。

type Form struct {
    Hour int
    Min  int
}
form.Min = fmt.Sprint(time.Min)

minsString := []string{"0","5","10","15","20","25","30","35","40","45","50","55"}

withの中でrangeを扱うには。。$に入れたらいいじゃないか

{{$minsString := .minsString}}
{{with $field := field "form.Min" .}}
<select name="{{$field.Name}}">
  {{range $index,$element := $minsString}}
  {{option $field $element $element}}
  {{end}}
</select>分
{{end}}

withだとプルダウンの中に「○分」と書けないな。。optionタグを普通に書くべきか。。

ならば

stringで扱いつつoptionで書けばスマートか?

{{$minflash := index .flash "form.Min"}}
{{$min := firstof $minflash .form.Min}}
<select name="form.Min">
{{range $index,$element := .minsString}}
  <option value="{{$element}}" {{if eq $element $min}}selected{{end}}>{{$element}}分</option>
{{end}}
</select>

メモ

  • firstof .. ドキュメントには書いてないがコミュニティで議論されて実装としてはある
    • 値がある場合はそっちを使うという三項演算子みたいなやつ
  • Flashの値はindexで取り出せる

結論

書きにくい。
新しく型を用意するのも面倒なので最初のFlashした値をintにさえ戻しておけばいいのではなかろうか?

色々試してみた結果、Templateではwithやrangeで扱えないと思っていた値も結構いけることがわかった。

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