英文:
html/template call method on value directly
问题
我想在模板中直接调用并打印Date
的Format
结果,而不需要为Foo
结构编写一个样板方法。
package main
import (
"html/template"
"os"
"time"
)
type Foo struct {
Date time.Time
}
func main() {
foo := Foo{time.Now()}
tmpl, err := template.New("test").Parse("{{.Date.Format \"2006-01-02\"}}")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, foo)
if err != nil {
panic(err)
}
}
英文:
I would like to call and print the result of Format on Date directly within the template without writing a boiler plate method for the Foo struct.
package main
import (
"html/template"
"os"
"time"
)
type Foo struct {
Date time.Time
}
func main() {
foo := Foo{time.Now()}
tmpl, err := template.New("test").Parse("{{.Date}}")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, foo)
if err != nil {
panic(err)
}
}
答案1
得分: 3
你可以在Date对象上调用.Format方法:
"{{.Date.Format \"Jan 2, 2006 at 3:04pm (MST) "}}"
package main
import (
"html/template"
"os"
"time"
)
type Foo struct {
Date time.Time
}
func main() {
foo := Foo{time.Now()}
tmpl, err := template.New("test").Parse("{{.Date.Format \"Jan 2, 2006 at 3:04pm (MST)\"}}")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, foo)
if err != nil {
panic(err)
}
}
英文:
You can call .Format on the Date Object:
"{{.Date.Format \"Jan 2, 2006 at 3:04pm (MST)\" }}"
http://play.golang.org/p/P4kKfZ5UN5
package main
import (
"html/template"
"os"
"time"
)
type Foo struct {
Date time.Time
}
func main() {
foo := Foo{time.Now()}
tmpl, err := template.New("test").Parse("{{.Date.Format \"Jan 2, 2006 at 3:04pm (MST)\" }}")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, foo)
if err != nil {
panic(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论