go - 无法在没有解析错误的情况下在 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 }}
它说它无法用第二行解析文件,但问题是什么?据我所知,我正在正确使用该命令。
解决方案
起初,问题似乎是由于:=
在已经存在的变量上使用了语法,但这不是问题,如本例所示:
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.000000001
2009-10-10 23:00:00 +0000 UTC<nil>
推荐阅读
- javascript - 如何让下拉菜单表现得像复选框?
- authentication - 如何将 Keycloak 连接到第三方身份验证服务以获取 id,然后从 KC 用户联合服务获取角色
- entity-framework - 当拦截的命令在事务内时,如何用户使用 EF 命令拦截器将数据保存到数据库
- docker - 基于环境变量的nginx条件代理传递
- javascript - 在 Windows 中使用 process.env 命令进行生产
- html - 我的地图上图像上的指针在我的 html 上不准确
- javascript - path.join() 产生重复或无
- javascript - 登录表单 HTML 中的关闭按钮不会隐藏表单,它只是将我带到 action 元素属性中的页面。我使用了html和js
- google-cloud-platform - Google Cloud GKE 节点池指标 instance_group/size ==
- java - 此类应在 android manifest 中提供默认构造函数(不带参数的公共构造函数)