dougua3706 2016-02-01 09:33
浏览 107
已采纳

html模板中的golang乘法算法

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?

  • 写回答

1条回答 默认 最新

  • douduan5086 2016-02-01 09:40
    关注

    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 <kbd>Go Playground</kbd>.

    $ 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?