html/template call method on value directly

huangapple go评论81阅读模式
英文:

html/template call method on value directly

问题

我想在模板中直接调用并打印DateFormat结果,而不需要为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)
	}
}

Playground

英文:

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)
	}
}

Playground

答案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)
	}
}

huangapple
  • 本文由 发表于 2014年6月7日 00:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/24087027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定