Range 在正确显示所有内容时无法迭代 true 吗?
Range can't iterate over true when it displays everything correctly?
我在使用 Go 模板时遇到了一个奇怪的问题。出于某种原因,当我使用 double range
时,它会停止在代码中渲染它下面的所有内容。
// Index.html
{{define "index"}}
{{range $k, $element := .Items}}
{{range $element}}
{{.Title}}
{{end}}
{{end}}
{{end}}
这是我的 Go 代码:
data := IndexData{
Items: items,
}
IndexTemplate := template.Must(template.New("skeleton.html").Funcs(FuncTemplate).ParseFiles("skeleton.html", "index.html"))
IndexTemplate.ExecuteTemplate(w, "skeleton", data)
它确实在我的页面上正确显示了数据并且没有错误。这里唯一的问题是它在显示最后一个项目后停止页面呈现。
在我的骨架中,我会这样显示我的模板,具体取决于他们访问的页面:
// Skeleton.html
{{define "skeleton"}}
{{block "index".}}{{end}}
{{block "account.register".}}{{end}}
{{block "account.login".}}{{end}}
{{block "account.profile".}}{{end}}
{{end}}
为什么显示范围内的最后一项后停止渲染?
编辑:
仅显示错误 executing "index" at <$element>: range can't iterate over true
编辑 2:
.Item
是一个包含以下内容的 map[string]interface{}
:
map[result:[map[Title:Hello World2 Content:Lorem ipsum dolor sit amet2...] map[Title:Hello World Content:Lorem ipsum dolor sit amet...]] success:true]
解决方案
我设法通过正确返回我需要使用的数据而不使用 success:true
部分以及将其用作 interface{}
来解决这个问题,因此我不必使用 2 个范围循环。
外部范围使用键 result
和 success
遍历映射。内部范围尝试迭代这些键的值。 success
的值为 true
。不可能对 bool 进行取值。
仅将模板范围更改为 result
:
{{define "index"}}
{{range .Items.result}}
{{.Title}}
{{end}}
{{end}}
此外,修改代码以检查和处理从ExecuteTemplate
返回的错误。
我在使用 Go 模板时遇到了一个奇怪的问题。出于某种原因,当我使用 double range
时,它会停止在代码中渲染它下面的所有内容。
// Index.html
{{define "index"}}
{{range $k, $element := .Items}}
{{range $element}}
{{.Title}}
{{end}}
{{end}}
{{end}}
这是我的 Go 代码:
data := IndexData{
Items: items,
}
IndexTemplate := template.Must(template.New("skeleton.html").Funcs(FuncTemplate).ParseFiles("skeleton.html", "index.html"))
IndexTemplate.ExecuteTemplate(w, "skeleton", data)
它确实在我的页面上正确显示了数据并且没有错误。这里唯一的问题是它在显示最后一个项目后停止页面呈现。
在我的骨架中,我会这样显示我的模板,具体取决于他们访问的页面:
// Skeleton.html
{{define "skeleton"}}
{{block "index".}}{{end}}
{{block "account.register".}}{{end}}
{{block "account.login".}}{{end}}
{{block "account.profile".}}{{end}}
{{end}}
为什么显示范围内的最后一项后停止渲染?
编辑:
仅显示错误 executing "index" at <$element>: range can't iterate over true
编辑 2:
.Item
是一个包含以下内容的 map[string]interface{}
:
map[result:[map[Title:Hello World2 Content:Lorem ipsum dolor sit amet2...] map[Title:Hello World Content:Lorem ipsum dolor sit amet...]] success:true]
解决方案
我设法通过正确返回我需要使用的数据而不使用 success:true
部分以及将其用作 interface{}
来解决这个问题,因此我不必使用 2 个范围循环。
外部范围使用键 result
和 success
遍历映射。内部范围尝试迭代这些键的值。 success
的值为 true
。不可能对 bool 进行取值。
仅将模板范围更改为 result
:
{{define "index"}}
{{range .Items.result}}
{{.Title}}
{{end}}
{{end}}
此外,修改代码以检查和处理从ExecuteTemplate
返回的错误。