在HTML文件中循环切片值

时间:2017-07-05 19:25:18

标签: go

我创建了一层struct和一个切片数组。

type blogs struct {
    id             int
    title          string
    featured_image string
    created_at     string
}

并在" xyz"内创建变量功能:

blog := blogs{}
blogData := []blogs{}

值为:

    rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by created_at desc limit 0,6")
    if err != nil {
        ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
    }        
    for rows.Next() {
        rcan := rows.Scan(&id, &title, &featured_image, &created_at)

        blog.id = id
        blog.title = title
        blog.featured_image = featured_image
        blog.created_at = created_at

        blogData = append(blogData, blog)
    }

现在,我已经通过" blogData"值为" html"模板和下面的iterating会出错:

  <ul>
  {{ range $value := .blogData }}
    <li>{{ $value.title }}</li>
  {{ end }}
  </ul>

错误:

template: master.html:18:5: executing "master.html" at <yield>: error calling yield: template: home.html:5:17: executing "home.html" at <$value.title>: title is an unexported field of struct type main.blogs

我如何打印&#34;标题&#34;以及我模板中blogData变量的其他值。

如果我打印$value,则会返回以下格式的所有值

{5 This is Title img/blog.jpg 2017-07-05T10:11:30+05:30 }

但我想分别打印titlefeatured_image和其他日期。

任何帮助将不胜感激。我正在使用&#34; github.com/get-ion/ion"框架

由于

1 个答案:

答案 0 :(得分:1)

要访问模板上的struct字段,必须将其导出为字段。将结构更新为 -

type blogs struct {
    ID             int
    Title          string
    Featured_image string
    Created_at     string
}

详细了解Exported/Unexported Identifiers In Go