带有小胡子的未排序列表的结构切片

Slice of structs to unsorted list with mustache

我有一个结构。

type DataKey struct {
    Id        int64     `db:"id"`
    UserId    string    `db:"user_id"`
    Data      string    `db:"data"`
    CreatedAt time.Time `db:"created_at"`
}

我创建了一片结构。

data := []DataKey{}

在执行 sql 查询并填充切片后,我尝试传递给 mustache 以构建我的列表。

mustache.RenderFileInLayout("templates/datakeys.html.mustache", "templates/layout.html.mustache", user, data)))

datakeys.html.mustache

<table class="table table-striped">
<thead>
    <tr>
        <th>#</th>
        <th>UserID</th>
        <th>DataKey</th>
        <th>CreatedAt</th>
    </tr>
</thead>
{{#DataKey}}
    <tr>
        <td>{{Id}}</td>
        <td>{{UserId}}</td>
        <td>{{Data}}</td>
        <td>{{CreatedAt}}</td>
    </tr>
{{/DataKey}}
</table>

我唯一得到的是 table header。此函数不会 return 错误,所以我不知道为什么它不喜欢这些数据。我也试过把它作为参考。

我不熟悉小胡子,但从它的角度来看,我认为 {{#DataKey}} 是错误的。

来自文档:

模板:

{{#repo}}
  <b>{{name}}</b>
{{/repo}}

哈希:

{
  "repo": [
    { "name": "resque" },
    { "name": "hub" },
    { "name": "rip" }
  ]
}

输出:

<b>resque</b>
<b>hub</b>
<b>rip</b>

我建议尝试以下方法

viewModel := struct{
    items []DataKey{}
}{
    data
}

mustache.RenderFileInLayout("templates/datakeys.html.mustache", "templates/layout.html.mustache", user, viewModel )))

然后将模板替换为

{{#items}}
    <tr>
        <td>{{Id}}</td>
        <td>{{UserId}}</td>
        <td>{{Data}}</td>
        <td>{{CreatedAt}}</td>
    </tr>
{{/items}}

这是未经测试的,可能不正确,但可能值得一试。我的猜测是 DataKey 不是模型上的 属性,因此无法评估。

为了更清楚而编辑:理论上

viewModel := struct{
    items []DataKey{}
}{
    data
}

会变成

{
    "items": [
        {...},{...} ... etc
    ]
}