Joh*_*son 5 algorithm templates go
我是 golang 新手。当我在 html/template 中使用乘法时遇到问题。一些代码如下。
模板代码:
{{range $i,$e:=.Items}}
<tr>
<td>{{add $i (mul .ID .Number)}}</td>
<td>{{.Name}}</td>
</tr>
{{end}}
Run Code Online (Sandbox Code Playgroud)
.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
}
Run Code Online (Sandbox Code Playgroud)
当我使用上面的代码时,它不会输出任何内容。但是当我在下面的数组之外使用代码时,它会输出 10 。
<html>
<body>
{{mul .Number .Number2}}
</html>
</body>
Run Code Online (Sandbox Code Playgroud)
我用谷歌搜索了很多。我找不到像我这样可用的。我想在 html/template 内部的数组中使用乘法。有人可以告诉我我的代码有什么问题吗?
template.Execute()
返回一个error
,您应该始终检查它。你会这样做吗:
模板:item.gtpl:3:33:在 <.Number> 处执行“item.gtpl”:Number 不是结构类型 main.Item 的字段
“问题”是{{range}}
将管道(点, .
)更改为当前项目,因此在{{range}}
:
{{add $i (mul .ID .Number)}}
Run Code Online (Sandbox Code Playgroud)
.Number
将引用您Item
类型的字段或方法,因为您正在循环遍历[]Item
. 但你的Item
类型没有这样的方法或字段。
使用$.Number
which将引用“顶级”Number
而不是当前值的字段Item
:
{{add $i (mul .ID $.Number)}}
Run Code Online (Sandbox Code Playgroud)
在Go Playground上尝试修改后的工作代码。
$
记录在text/template
:
当执行开始时,$被设置为传递给Execute的数据参数,即点的起始值。