作品:
{{ $temp := timestampToDate $var.date }}
{{ $temp.Format 2006/01/02 }}
Run Code Online (Sandbox Code Playgroud)
不行
{{ $temp := timestampToDate $var.date }}
{{ $temp := $temp.AddDate(0,-1,0) }}
{{ $temp.Format 2006/01/02 }}
Run Code Online (Sandbox Code Playgroud)
它说它不能用第二行解析文件,但问题是什么?就我所见,我正确使用命令.
起初看起来似乎问题是由于:=
在已经存在的变量上使用语法,但这不是问题,因为这个例子说明:
t := template.Must(template.New("").Parse(`{{$temp := "aa"}}{{$temp}}
{{$temp := "bb"}}{{$temp}}`))
fmt.Println(t.Execute(os.Stdout, nil))
Run Code Online (Sandbox Code Playgroud)
哪些输出(在Go Playground上试试):
aa
bb<nil>
Run Code Online (Sandbox Code Playgroud)
但是当然,如果变量已经存在,则应该使用=
赋值,因为:=
它将创建一个新变量,如果在另一个块(例如{{range}}
或{{if}}
)内发生,则更改的值不会保留在块之外.
真正的问题是函数调用语法:
{{ $temp := $temp.AddDate(0,-1,0) }}
Run Code Online (Sandbox Code Playgroud)
在Go模板中,您不能使用普通的调用语法,您只需枚举参数,将空格分隔,例如:
{{ $temp = $temp.AddDate 0 -1 0 }}
Run Code Online (Sandbox Code Playgroud)
返回的错误Template.Execute()
表明:
panic: template: :3: unexpected "(" in operand
Run Code Online (Sandbox Code Playgroud)
详情请见template/Pipelines
:
命令是一个简单的值(参数)或函数或方法调用,可能有多个参数:
Run Code Online (Sandbox Code Playgroud)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))
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-10-10 23:00:00 +0000 UTC<nil>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
48 次 |
最近记录: |