在使用html/template时,执行格式化时间的切片。

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

Execute formatted time in a slice with html/template

问题

我正在制作一个简单的Web服务器来托管我的博客,但无论我怎么做,都无法将正确格式的时间插入到我的html/template中。

这是我做的事情:

我创建了这个结构体:

type Blogpost struct {
    Title   string
    Content string
    Date    time.Time
}

接下来,我创建了这个小函数,它从Appengine Datastore中检索具有相应标题/日期的博客文章,并将其作为切片返回:

func GetBlogs(r *http.Request, max int) []Blogpost {
    c := appengine.NewContext(r)
    q := datastore.NewQuery("Blogpost").Order("-Date").Limit(max)
    bp := make([]Blogpost, 0, max)
    q.GetAll(c, &bp)
    return bp
}

最后,在blogHandler中,我使用从Appengine Datastore检索到的数据创建一个切片:

blogs := GetBlogs(r, 10)

现在,当我像这样执行名为"blog"的模板时,博客的日期被解析为默认日期:

blog.Execute(w, blogs) // 得到的日期形式为:2013-09-03 16:06:48 +0000 UTC

所以,作为一个Golang新手,我认为以下函数会给我想要的结果:

blogs[0].Date = blogs[0].Date.Format("02-01-2006 15:04:05") // 返回结果类似于:03-09-2013 16:06:48,至少在打印格式化日期时是这样的。

然而,这会导致类型冲突,我尝试使用以下方式解决:

blogs[0].Date, _ = time.Parse("02-01-2006 15:04:05", blogs[0].Date.Format("02-01-2006 15:04:05")) // 再次返回:2013-09-03 16:06:48 +0000 UTC

这可能是我又忽视的一些新手问题,但我就是看不出来为什么我不能覆盖切片中的time.Time类型,或者至少以我想要的格式打印它。

英文:

I'm making this simple webserver that can host my blog, but whatever I do; I can not execute a proper formatted time into my html/template.

Here's what I do:

I've created this struct:

type Blogpost struct {
    Title   string
    Content string
    Date    time.Time
}

Next up I've created this little func that retrieves the blogposts with corresponding title/dates from the Appengine Datastore and return that as a slice:

func GetBlogs(r *http.Request, max int) []Blogpost {
    c := appengine.NewContext(r)
    q := datastore.NewQuery("Blogpost").Order("-Date").Limit(max)
    bp := make([]Blogpost, 0, max)
    q.GetAll(c, &bp)
    return bp
}

Finally, in the blogHandler I create a slice based on the retrieved data from the Appengine Datastore using:

blogs := GetBlogs(r, 10)

Now when I Execute my template called blog like this, the dates of the blogs are being parsed as default dates:

blog.Execute(w, blogs) // gives dates like: 2013-09-03 16:06:48 +0000 UTC

So, me, being the Golang n00b that I am, would say that a function like the following would give me the result I want

blogs[0].Date = blogs[0].Date.Format("02-01-2006 15:04:05") // Would return like 03-09-2013 16:06:48, at least when you print the formatted date that is.

However that results in a type conflict ofcourse, which I tried to solve using:

blogs[0].Date, _ = time.Parse("02-01-2006 15:04:05", blogs[0].Date.Format("02-01-2006 15:04:05")) // returns once again: 2013-09-03 16:06:48 +0000 UTC

It is probably some n00b thing I oversaw once again, but I just can't see how I can't override a time.Time Type in a slice or at least print it in the format that I want.

答案1

得分: 78

在寻找一种类似的功能来简单地格式化和渲染time.Time类型在html/template中时,我偶然发现Go的模板解析器允许在渲染time.Time类型时调用方法,但有一些限制。

例如:

type Post struct {
    Id        int
    Title     string
    CreatedOn time.Time
}

// post 是一个 &Post。在我的情况下,我从一个具有日期时间列的 PostgreSQL 表中获取了该字段的值,
// 数据库中的值为 2015-04-04 20:51:48

template.Execute(w, post)

可以在模板中使用该时间,如下所示:

<span>{{ .CreatedOn }}</span>
<!-- 输出:2015-04-04 20:51:48 +0000 +0000 -->

<span>{{ .CreatedOn.Format "2006 Jan 02" }}</span>
<!-- 输出:2015 Apr 04 -->

<span>{{ .CreatedOn.Format "Jan 02, 2006" }}</span>
<!-- 输出:Apr 04, 2015 -->

<span>{{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}</span>
<!-- 输出:Apr 04, 2015 20:51:48 UTC -->

注意:我的Go版本是go1.4.2 darwin/amd64

希望对其他人有所帮助。

英文:

While I looking for a similar functionality to simply format and render a time.Time type in a html/template, I fortuitously discovered that go's template parser allows methods to be called under certain restrictions when rendering a time.Time type.

For example;

type Post struct {
    Id        int
    Title     string
    CreatedOn time.Time
}

// post is a &amp;Post. in my case, I fetched that from a postgresql
// table which has a datetime column for that field and
// value in db is 2015-04-04 20:51:48

template.Execute(w, post)

and it's possible to use that time in a template like below:

&lt;span&gt;{{ .CreatedOn }}&lt;/span&gt;
&lt;!-- Outputs: 2015-04-04 20:51:48 +0000 +0000 --&gt;

&lt;span&gt;{{ .CreatedOn.Format &quot;2006 Jan 02&quot; }}&lt;/span&gt;
&lt;!-- Outputs: 2015 Apr 04 --&gt;

&lt;span&gt;{{ .CreatedOn.Format &quot;Jan 02, 2006&quot; }}&lt;/span&gt;
&lt;!-- Outputs: Apr 04, 2015 --&gt;

&lt;span&gt;{{.CreatedOn.Format &quot;Jan 02, 2006 15:04:05 UTC&quot; }}&lt;/span&gt;
&lt;!-- Outputs: Apr 04, 2015 20:51:48 UTC --&gt;

As a note; my go version is go1.4.2 darwin/amd64

Hope it helps others.

答案2

得分: 40

你的Date字段的类型是time.Time。如果你将其格式化为字符串,然后再解析回来,你仍然会得到一个time.Time值,当模板执行调用其String方法时,它仍然会以默认方式打印,所以这并没有真正解决你的问题。

解决的方法是,不是提供模板一个时间值,而是提供一个格式化的时间字符串本身,你可以用多种方式实现这一点。例如:

  • 在你的博客文章类型中添加一个名为FormattedDate或类似的方法,该方法返回一个以你喜欢的样式正确格式化的字符串。这是最简单、可能也是最好的方式,如果你没有一个复杂的用例的话。

  • 在你的博客类型中添加一个名为FormattedDate或类似的字符串字段;这与上述选项非常相似,但你必须小心设置和更新字段,所以我更喜欢方法选项。

  • 如果你想在模板中以多种方式格式化时间值,你还可以选择定义一个模板格式化函数,这样你可以做类似于{{post.Date | fdate "02-01-2006 15:04:05"}}的操作。有关如何实现这一点的详细信息,请参阅Template.FuncsFuncMap类型此示例的文档。

更新: 第一种选项的示例代码:http://play.golang.org/p/3QYdrDQ1YO

英文:

Your Date field has type time.Time. If you format it as a string, and parse it back, you'll once again get a time.Time value, which will still print the default way when the template execution calls its String method, so it's not really solving your problem.

The way to solve it is by providing the template with the formatted time string itself instead of a time value, and you can do that in multiple ways. For example:

  • Add a method to your blog post type named FormattedDate or similar, which returns a string properly formatted in the style of your preference. That's the easiest, and probably the nicest way if you don't have a fancy use case.

  • Add a string field to your blog type named FormattedDate or similar; that's very similar to the above option, but you have to be careful to set and update the field whenever necessary, so I'd prefer the method option instead.

  • If you'd like to format time values in multiple ways within the template, you might also opt to define a template formatter function, so that you might do something like {{post.Date | fdate &quot;02-01-2006 15:04:05&quot;}}. See the documentation on Template.Funcs, the FuncMap type, and this example for details on how to do that.

Update: Sample code for the first option: http://play.golang.org/p/3QYdrDQ1YO

答案3

得分: 4

如果在模板中输出一个 time.Time 类型的变量,它会被转换为字符串。这个默认的转换就是你看到的结果。如果你需要不同的格式,有两种可能性:

  1. 在你的 Blogpost 结构体中添加一个 FormattedDate string 字段,并通过 Date.Format(whatever) 方法从 Date 字段中填充它。
  2. 在你的模板中编写并注册一个格式化过滤器(参见 http://golang.org/pkg/html/template/#Template.Funcs),然后使用它。
英文:

If you output a time.Time in a template it will be converted to a string. This default conversion is what you see. If you need a different format you have two possibilites:

  1. Add a `FormatedDate string field to your Blogpost and populate it from Date via Date.Format(whatever)
  2. Write and register a formatting filter` in your template (see http://golang.org/pkg/html/template/#Template.Funcs) and use this.

huangapple
  • 本文由 发表于 2013年9月4日 01:49:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/18598480.html
匿名

发表评论

匿名网友

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

确定