首页 > 解决方案 > 在 golang 模板中使用 null.Time 值

问题描述

我正在使用 gopkg.in/guregu/null.v4 从 Postgres DB 获取一些数据,结果恢复正常,我可以将它们转换为 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}} 

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

标签: gotemplatesgo-templates

解决方案


首先,您正在使用html/templatewhich 提供上下文相关的转义,这就是您看到这些&#43;序列的原因。如果您想要文本输出,请text/template改用。有关详细信息,请参阅将 `<` 不必要地转义为 `<` 而不是 `>` 的模板

接下来,null.Time不只是一个简单的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上尝试一下。


推荐阅读