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 +0000 UTC m=+0.000000001
2009-10-10 23:00:00 +0000 UTC<nil>