dtiu94034 2011-05-29 05:50 采纳率: 0%
浏览 318
已采纳

循环遍历模板中的对象数组(转到)

I'm passing a struct (one element is an array of Category objects) to the template for rendering. In the template, I have code that looks something like this:

{.repeated section Categories}
    <p>{@}</p>
{.end}

However, each Category has a few of its own elements that I need to be able to access (Title for instance). I have tried things like {@.Title} but I can't seem to find the proper syntax for accomplishing this. How do I access members of data in an array during a loop in a template?

  • 写回答

1条回答 默认 最新

  • dreamwind1985 2011-05-30 07:13
    关注

    You can just write {Title}.

    Whenever the template package encounters an identifier, it tries to look it up in the current object and if it doesn't find anything it tries the parent (up to the root). The @ is just there if you wan't to access the current object as a whole and not one of its attributes.

    Since I'm not used to the template package either, I've created a small example:

    type Category struct {
        Title string
        Count int
    }
    
    func main() {
        tmpl, _ := template.Parse(`
            {.repeated section Categories}
                <p>{Title} ({Count})</p>
            {.end}
        `, nil)
        categories := []Category{
            Category{"Foo", 3},
            Category{"Bar", 5},
        }
        tmpl.Execute(os.Stdout, map[string]interface{} {
            "Categories": categories,
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮