为了账号安全,请及时绑定邮箱和手机立即绑定

为什么传递的变量没有在 html/template 中呈现?

为什么传递的变量没有在 html/template 中呈现?

Go
阿波罗的战车 2023-08-07 14:58:19
我不明白为什么传递的变量没有用 html/template 渲染这是浏览器中呈现的内容:这是所有传递的变量: [0xc0000a8ec0 0xc0000a8f80 0xc0000a9040 0xc0000a9100]城市 人口 州 国家 首都这是日志:$ go run main.go2019/11/27 11:00:39 **** => &city has &main.City{Name:"Washington D.C.", State:"", Country:"USA", Capital:false, Population:680000} before appending to cities ****2019/11/27 11:00:39 **** => &city has &main.City{Name:"Los Angeles", State:"CA", Country:"USA", Capital:false, Population:3900000} before appending to cities ****2019/11/27 11:00:39 **** => &city has &main.City{Name:"San Francisco", State:"CA", Country:"USA", Capital:false, Population:860000} before appending to cities ****2019/11/27 11:00:39 **** => &city has &main.City{Name:"Tokyo", State:"", Country:"Japan", Capital:true, Population:9000000} before appending to cities ******** => cities outside {} has 4这是处理函数:func indexHandler(w http.ResponseWriter, r *http.Request) {    projectID := "XXXXXXXXXXXXXX"    ctx := context.Background()    client, _ := firestore.NewClient(ctx, projectID)    query := client.Collection("cities").Documents(ctx)    defer query.Stop()    cities := make([]*City, 0)    for {        doc, err := query.Next()        if err == iterator.Done {            break        }        c := doc.Data()        // is there an easier way to populate the city struct        city := City{            Name:       c["name"].(string),            Country:    c["country"].(string),            Population: c["population"].(int64),        }        // This is my ugly solution to dealing with nil value from Firestore        _, ok := c["capital"]        if ok {            city.Capital = c["capital"].(bool)        }        state, ok := c["state"].(string)        if ok {            city.State = state        }        log.Printf("**** => &city has %#v before appending to cities ****", &city)        cities = append(cities, &city)    }    fmt.Printf("**** => cities outside {} has %d", len(cities))    indexTemplate.Execute(w, cities)    }
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

永远不要遗漏错误,检查indexTemplate.Execute(w, cities)返回的内容。它可能揭示了原因:

cities作为数据传递,这是一个切片。没有cities它的领域或方法。传递的数据成为,因此您必须在点上进行范围。

代替:

{{ range .cities }}

使用:

{{ range . }}


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信