乍一看,问题似乎是由于对:=已存在的变量使用语法,但这不是问题,如本例所示:t := template.Must(template.New("").Parse(`{{$temp := "aa"}}{{$temp}}
{{$temp := "bb"}}{{$temp}}`))
fmt.Println(t.Execute(os.Stdout, nil))哪些输出(在Go Playground上尝试):aa
bb<nil>但是当然,如果变量已经存在,你应该使用赋值=,因为这:=将创建一个新变量,如果发生在另一个块内(例如{{range}}or {{if}}),更改的值将不会保留在块外。真正的问题是函数调用语法:{{ $temp := $temp.AddDate(0,-1,0) }}在 Go 模板中你不能使用普通的调用语法,你只需要枚举参数,用空格分隔,例如:{{ $temp = $temp.AddDate 0 -1 0 }}返回的错误Template.Execute()表明:panic: template: :3: unexpected "(" in operand这在以下位置有详细说明template/Pipelines:命令是一个简单的值(参数)或一个函数或方法调用,可能带有多个参数: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.例子: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))输出(在Go Playground上尝试):2009-11-10 23:00:00 +0000 UTC m=+0.0000000012009-10-10 23:00:00 +0000 UTC<nil>