首页 > 解决方案 > 无法在没有解析错误的情况下在 Google Go 中添加时间到日期

问题描述

作品:

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

不工作

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

它说它无法用第二行解析文件,但问题是什么?据我所知,我正在正确使用该命令。

标签: gogo-templates

解决方案


起初,问题似乎是由于:=在已经存在的变量上使用了语法,但这不是问题,如本例所示:

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 &#43;0000 UTC m=&#43;0.000000001

2009-10-10 23:00:00 &#43;0000 UTC<nil>

推荐阅读