1 回答
TA贡献1798条经验 获得超7个赞
如果它是强制值,您应该在渲染模板之前对其进行验证。
但是,如果它是可选的和/或您正在编写模板驱动的应用程序,那么您至少有两个选项来实现您想要的。
仅使用零值
充分利用零值:因为time.Time
这就是epoch。因此,假设您不能拥有StartDate
过去的日期,您可以比较您的 StartDate 是否在纪元之后。
package main
import (
"html/template"
"os"
"time"
)
// Note the call to the `After` function of the date.
const templateText = `
{{ if .Data.StartDate.After .Epoch }}
<div class="box date-row" id="startdate-{{ .Data.DepartureTimeID }}">{{ .Data.StartDate.Format "2006-01-02" }}</div>
{{ else }}
<div class="box date-row" id="startdate-{{ .Data.DepartureTimeID }}">No date</div>
{{ end }}
`
func main() {
// shortcut for the sake of brevity.
tmpl := template.Must(template.New("titleTest").Parse(templateText))
// Create an anonymous wrapper struct for your data and the additional
// time value you need to compare against
tcx := struct {
// This of course may be of the type you actually use.
Data struct {
StartDate time.Time
DepartureTimeID int
}
Epoch time.Time
}{
Data: struct {
StartDate time.Time
DepartureTimeID int
}{time.Now(), 1},
Epoch: time.Time{},
}
tmpl.Execute(os.Stdout, tcx)
}
package main
import (
"html/template"
"os"
"log"
"time"
)
const templateText = `
{{ if afterEpoch .StartDate }}
<div class="box date-row" id="startdate-{{ .DepartureTimeID }}">{{ .StartDate.Format "2006-01-02" }}</div>
{{ else }}
<div class="box date-row" id="startdate-{{ .DepartureTimeID }}"></div>
{{ end }}
`
func AfterEpoch(t time.Time) bool {
return t.After(time.Time{})
}
type yourData struct {
DepartureTimeID int
StartDate time.Time
}
func main() {
funcMap := template.FuncMap{
"afterEpoch": AfterEpoch,
}
tmpl := template.Must(template.New("fmap").Funcs(funcMap).Parse(templateText))
log.Println("First run")
tmpl.Execute(os.Stdout, yourData{1, time.Now()})
log.Println("Second run")
tmpl.Execute(os.Stdout, yourData{DepartureTimeID:1})
}
编辑:
当然,您也可以对第二种解决方案使用管道表示法,即 by ,以提高可读性,恕我直言:{{ if .StartDate | afterEpoch }}
- 1 回答
- 0 关注
- 127 浏览
添加回答
举报