douyi7283 2018-09-26 17:22
浏览 72
已采纳

正确显示所有内容时,范围不能迭代true?

I'm having a weird issue with Go templates. For some reason when I use double range it stops rendering everything below it in the code.

// Index.html
{{define "index"}}
    {{range $k, $element := .Items}}
        {{range $element}}
            {{.Title}}
        {{end}}
    {{end}}
{{end}}

This is my Go code:

data := IndexData{
    Items: items,
}

IndexTemplate := template.Must(template.New("skeleton.html").Funcs(FuncTemplate).ParseFiles("skeleton.html", "index.html"))
IndexTemplate.ExecuteTemplate(w, "skeleton", data)

It does show the data correctly on my page and there are no errors. The only problem here is that it stops the rendering of the page after the last item is displayed.

In my skeleton I display my templates like this, depending on what page they're visiting:

// Skeleton.html
{{define "skeleton"}}
    {{block "index".}}{{end}}
    {{block "account.register".}}{{end}}
    {{block "account.login".}}{{end}}
    {{block "account.profile".}}{{end}}
{{end}}

Why does it stop rendering after the last item is displayed from the range?

EDIT:

Only error displayed is executing "index" at <$element>: range can't iterate over true

EDIT 2:

.Item is a map[string]interface{} that contains the following:

map[result:[map[Title:Hello World2 Content:Lorem ipsum dolor sit amet2...] map[Title:Hello World Content:Lorem ipsum dolor sit amet...]] success:true]

Solution

I managed to solve this by properly returning the data I need to use without the success:true part as well as using it as interface{} so I don't have to use 2 range loops.

  • 写回答

1条回答 默认 最新

  • dongqiang5541 2018-09-26 17:53
    关注

    The outer range iterates over a map with the keys result and success. The inner range attempts to iterate over the values for these keys. The value for success is true. It's not possible to range on a bool.

    Change the template range over result only:

    {{define "index"}}
            {{range .Items.result}}
                {{.Title}}
            {{end}}
    {{end}}
    

    Also, modify the code to check and handle the error returned from ExecuteTemplate.

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

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?