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.

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图