dongmi4809 2015-03-26 15:38
浏览 6
已采纳

切片结构到未排序的列表,留着小胡子

I have a struct.

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

I create a slice of structs.

data := []DataKey{}

After doing a sql query and filling the slices I try to pass to mustache to build my list.

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>

The only thing I get is the table header. This function does not return an error so I don't know why it didn't like the data. I have also tried passing it in as a reference.

  • 写回答

1条回答 默认 最新

  • dsuikgi9199 2015-03-26 16:37
    关注

    Im not familiar with mustache but from looking at it I think the {{#DataKey}} is wrong.

    From the docs:

    Template:

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

    Hash:

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

    Output:

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

    I'd suggest trying the following

    viewModel := struct{
        items []DataKey{}
    }{
        data
    }
    
    mustache.RenderFileInLayout("templates/datakeys.html.mustache", "templates/layout.html.mustache", user, viewModel )))
    

    and then replace the template with

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

    This is untested and might not be correct, but might be worth trying. My guess is that DataKey isn't a property on the model hence it's failing to evaluate.

    Edit for more clarity: In theory

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

    will become

    {
        "items": [
            {...},{...} ... etc
        ]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名