【问题标题】:Use null.Time values in a golang template在 golang 模板中使用 null.Time 值
【发布时间】:2021-11-13 21:46:39
【问题描述】:

我正在使用 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}} 

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

【问题讨论】:

    标签: go templates go-templates


    【解决方案1】:

    首先,您使用的是html/template,它提供了上下文相关的转义,这就是您看到那些&amp;#43; 序列的原因。如果您想要文本输出,请改用text/template。详情见Template unnecessarily escaping `<` to `&lt;` but not `>`

    接下来,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 上试试。

    【讨论】:

      猜你喜欢
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2018-11-14
      相关资源
      最近更新 更多