1 回答

TA貢獻1921條經驗 獲得超9個贊
乍一看,問題似乎是由于對:=
已存在的變量使用語法,但這不是問題,如本例所示:
t?:=?template.Must(template.New("").Parse(`{{$temp?:=?"aa"}}{{$temp}} {{$temp?:=?"bb"}}{{$temp}}`)) fmt.Println(t.Execute(os.Stdout,?nil))
哪些輸出(在Go Playground上嘗試):
aa bb<nil>
但是當然,如果變量已經存在,你應該使用賦值=
,因為這:=
將創(chuàng)建一個新變量,如果發(fā)生在另一個塊內(例如{{range}}
or?{{if}}
),更改的值將不會保留在塊外。
真正的問題是函數(shù)調用語法:
{{?$temp?:=?$temp.AddDate(0,-1,0)?}}
在 Go 模板中你不能使用普通的調用語法,你只需要枚舉參數(shù),用空格分隔,例如:
{{?$temp?=?$temp.AddDate?0?-1?0?}}
返回的錯誤Template.Execute()
表明:
panic:?template:?:3:?unexpected?"("?in?operand
這在以下位置有詳細說明template/Pipelines
:
命令是一個簡單的值(參數(shù))或一個函數(shù)或方法調用,可能帶有多個參數(shù):
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>
- 1 回答
- 0 關注
- 166 瀏覽
添加回答
舉報