在 golang 模板中使用 null.Time 值

Use null.Time values in a golang template

我正在使用 gopkg.in/guregu/null.v4 从 Postgres 数据库中获取一些数据,结果返回正常,我可以将它们转换成 json 格式,世界就是很高兴...但是,我正在尝试使用模板通过电子邮件发送结果,但遇到了问题。

结构是(部分)

type DataQuery struct {
     Date null.Time `json:"DateTime"`
....

模板是

{{define "plainBody"}}
Hi,

Here are the results for the check run for today.

The number of rows returned is {{.Rows}}

The data is
{{ range .Data}}
    {{.Date}}
{{end}}

{{end}}

而 运行 该模板的结果是

Hi,

Here are the results for the check run for today.

The number of rows returned is 57

The data is

    {{2021-09-13 00:00:00 +0000 +0000 true}}

    {{2021-08-16 00:00:00 +0000 +0000 true}}

    {{2021-09-19 00:00:00 +0000 +0000 true}}

    {{2021-09-18 00:00:00 +0000 +0000 true}}

我尝试使用 {{.Date.EncodeText}} 并以

结束
 [50 48 50 49 45 48 57 45 49 51 84 48 48 58 48 48 58 48 48 90]

    [50 48 50 49 45 48 56 45 49 54 84 48 48 58 48 48 58 48 48 90]

    [50 48 50 49 45 48 57 45 49 57 84 48 48 58 48 48 58 48 48 90]

对于日期时间字段(可能是字符串的 [] 字节,但我不确定。

如果我使用 {{Date.Value}} 我得到 2021-09-13 00:00:00 +0000 +0000

其他字段类型(字符串、整数、浮点数)都可以正常工作

{{Variable.ValueOrZero}} 

我想我已经很接近了..但不能完全破解日期时间字段

首先,您正在使用 html/template which provides context-sensitive escaping, that's why you're seeing those + sequences. If you want text output, use text/template instead. For details, see

接下来,null.Time is not just a simple time.Time值,它也包装了其他字段(时间是否有效)。当简单地输出它时,该有效字段也将被渲染(输出中的 true 文本)。

您只能呈现其 Time 字段:{{.Date.Time}}.

经过这些更改,输出将是例如:

Hi,

Here are the results for the check run for today.

The number of rows returned is 2

The data is

    2021-09-20 12:10:00 +0000 UTC

    2021-10-11 13:50:00 +0000 UTC

Go Playground 上试用。