Home > Blockchain >  Use null.Time values in a golang template
Use null.Time values in a golang template

Time:09-22

I'm using gopkg.in/guregu/null.v4 to get some data from a Postgres DB and the results are coming back fine, and I can put them into json format and the world is happy... however, I'm trying to email the results using a template and have hit a problem.

The structure is (partially)

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

The template is

{{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}}

And the results of running that template are

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}}

I tried using {{.Date.EncodeText}} and ended up with

 [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]

For the datetime fields (which might be a []byte of the strings but I'm not sure.

If I use {{Date.Value}} I get 2021-09-13 00:00:00 +0000 +0000

The other field types (string, int, float) all work fine with

{{Variable.ValueOrZero}} 

I think I'm close.. but can't quite crack it for the date time fields

CodePudding user response:

First, you are using html/template which provides context-sensitive escaping, that's why you're seeing those &#43; sequences. If you want text output, use text/template instead. For details, see Template unnecessarily escaping `<` to `&lt;` but not `>`

Next, null.Time is not just a simple time.Time value, it wraps other fields too (whether the time is valid). When simply outputting it, that valid field will also be rendered (the true texts in your output).

You may render only its Time field: {{.Date.Time}}.

With these changes output will be for example:

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

Try it on the Go Playground.

  • Related