gpt4 book ai didi

algorithm - html模板中的golang乘法算法

转载 作者:IT王子 更新时间:2023-10-29 01:10:19 44 4
gpt4 key购买 nike

我是 golang 的新手。我在 html/template 中使用乘法时遇到问题。一些代码如下。

模板代码:

 {{range $i,$e:=.Items}}
<tr>
<td>{{add $i (mul .ID .Number)}}</td>
<td>{{.Name}}</td>
</tr>
{{end}}

.go代码

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
}

当我使用上面的代码时,它不会输出任何内容。但是当我在下面的数组外使用代码时,它会输出 10。

<html>
<body>
{{mul .Number .Number2}}
</html>
</body>

我经常用谷歌搜索。我找不到像我一样可用的。我想在 html/template 中的数组中使用乘法。有人可以告诉我我的代码有什么问题吗?

最佳答案

template.Execute()返回 error ,你应该经常检查。你会这样做吗:

template: item.gtpl:3:33: executing "item.gtpl" at <.Number>: Number is not a field of struct type main.Item

“问题”是 {{range}} 将管道(.)更改为当前项,因此在 {{range}} 内:

{{add $i (mul .ID .Number)}}

.Number 将引用您的 Item 类型的字段或方法,因为您正在遍历 []Item。但是您的 Item 类型没有这样的方法或字段。

使用 $.Number 将引用“顶级”Number 而不是当前 Item 值的字段:

{{add $i (mul .ID $.Number)}}

Go Playground 上尝试修改后的工作代码.

$ 记录在 text/template :

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

关于algorithm - html模板中的golang乘法算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127051/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com