-3

Works:

{{ $temp := timestampToDate $var.date }}
{{ $temp.Format 2006/01/02 }}

Doesn't work

{{ $temp := timestampToDate $var.date }}
{{ $temp := $temp.AddDate(0,-1,0) }}    
{{ $temp.Format 2006/01/02 }}

It says it can't parse the file with the second line but what's the issue? I'm using the command correctly as far as I can see.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34

1 Answers1

7

At first it may seem the problem is due to using := syntax on an already existing variable, but that is not a problem, as this example illustrates:

t := template.Must(template.New("").Parse(`{{$temp := "aa"}}{{$temp}}
{{$temp := "bb"}}{{$temp}}`))

fmt.Println(t.Execute(os.Stdout, nil))

Which outputs (try it on the Go Playground):

aa
bb<nil>

But of course, if the variable already exists, you should use the = assignment, because the := will create a new variable, which if happens inside another block (e.g. {{range}} or {{if}}), the changed value will not remain outside the block.

The real problem is the function calling syntax:

{{ $temp := $temp.AddDate(0,-1,0) }}

In Go templates you can't use the normal call syntax, you just have to enumerate the arguments, white-space separated, e.g.:

{{ $temp = $temp.AddDate 0 -1 0 }}

The error returned by Template.Execute() indicates this:

panic: template: :3: unexpected "(" in operand

This is detailed at template/Pipelines:

A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

Argument
     The result is the value of evaluating the argument.
.Method [Argument...]
     The method can be alone or the last element of a chain but,
     unlike methods in the middle of a chain, it can take arguments.
     The result is the value of calling the method with the
     arguments:
         dot.Method(Argument1, etc.)
functionName [Argument...]
     The result is the value of calling the function associated
     with the name:
         function(Argument1, etc.)
     Functions and function names are described below.

Example:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "now": time.Now,
}).Parse(`{{$temp := now}}
{{$temp}}
{{$temp = $temp.AddDate 0 -1 0}}
{{$temp}}`))

fmt.Println(t.Execute(os.Stdout, nil))

Output (try it on the Go Playground):

2009-11-10 23:00:00 &#43;0000 UTC m=&#43;0.000000001

2009-10-10 23:00:00 &#43;0000 UTC<nil>
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • Superb. Thank you for the clarification on assignments and also how to properly call functions. Clearly, I have a lot to learn about this syntax. – not_a_generic_user Jan 14 '19 at 13:33