Reputation: 146
I am new for golang. I met a problem when I use multiplication in html/template. Some code like below.
template code:
{{range $i,$e:=.Items}}
<tr>
<td>{{add $i (mul .ID .Number)}}</td>
<td>{{.Name}}</td>
</tr>
{{end}}
.go code
type Item struct{
ID int
Name string
}
func init() {
itemtpl,_:=template.New("item.gtpl").
Funcs(template.FuncMap{"mul": Mul, "add": Add}).
ParseFiles("./templates/item.gtpl")
}
func itemHandle(w http.ResponseWriter, req *http.Request) {
items:=[]Item{Item{1,"name1"},Item{2,"name2"}}
data := struct {
Items []Item
Number int
Number2 int
}{
Items: items,
Number: 5,
Number2: 2,
}
itemtpl.Execute(w, data)
}
func Mul(param1 int, param2 int) int {
return param1 * param2
}
func Add(param1 int, param2 int) int {
return param1 + param2
}
It will output nothing when I use the code above. But It will output 10 when I use the code outside of array below.
<html>
<body>
{{mul .Number .Number2}}
</html>
</body>
I google a lot. I cannot find the usable like mine. I want to use multiplication in array inside of html/template. Can someone tell me what is wrong with my code?
Upvotes: 5
Views: 4722
Reputation: 418505
template.Execute()
returns an error
, you should always check that. Would you have done so:
template: item.gtpl:3:33: executing "item.gtpl" at <.Number>: Number is not a field of struct type main.Item
The "problem" is that {{range}}
changes the pipeline (the dot, .
) to the current item, so inside the {{range}}
:
{{add $i (mul .ID .Number)}}
.Number
will refer to a field or method of your Item
type since you are looping over a []Item
. But your Item
type has no such method or field.
Use $.Number
which will refer to the "top-level" Number
and not a field of the current Item
value:
{{add $i (mul .ID $.Number)}}
Try your modified, working code on the Go Playground.
$
is documented at text/template
:
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
Upvotes: 3