go - 在 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}}
我想我已经接近了..但不能完全破解日期时间字段
解决方案
首先,您正在使用html/template
which 提供上下文相关的转义,这就是您看到这些+
序列的原因。如果您想要文本输出,请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上尝试一下。
推荐阅读
- javascript - 无法读取 null 0 的属性“标题”
- php - 如果未找到 ID 条目,MySQL 显示消息
- c# - 在重定向到其他页面时运行异步方法
- reactjs - 如何根据 makeStyles 中的“theme.palette.type”更改链接颜色?
- firebase - 您可以在复合查询中使用两次 whereIn 条件吗?
- redux - 在 redux 中存储计算值的位置
- android - 如何使用 volley 库在 android 中访问受密码保护的 URL
- python - Django FormView 传递参数和上下文
- python - Python,打印执行两次
- node.js - ReactJs 调用 NodeJs api 失败,错误 - 'keycloak-token' 未定义?