dongshan0202405 2016-09-07 10:50
浏览 17
已采纳

访问我模板中的结构数组

I'm passing an array of structs to my template, the data is there but I can't find a way to access specific data, I tried many things already, here it is

My Struct

type Data struct {
  Destination string
  IData interface{}
}

then in my controller I have

users := []models.User {}

userRow := models.User{Name: "jon", Email: "jon@mail.com"}
users = append(users, userRow)
users2 := users

data := models.Data{
    Destination: "content",
    IData: users,
}

data2 := models.Data{
    Destination: "content",
    IData: users2,
}

dataFinal := []models.Data{}
dataFinal = append(dataFinal, data)
dataFinal = append(dataFinal, data2)

and this is my template, though this didn't seem to work, it does show the raw data but can't seem to access the name specifically.

{{define "content"}}
<h2>THIS IS THE BODY CONTENT</h2>

<ul>
    {{.}}
    {{range .}}
    <li>{{.}}</li>
    {{end}}
</ul>
{{end}}

edit: project: https://github.com/og2/go-og2-mvc

you may wanna run:

go get github.com/go-sql-driver/mysql

go get github.com/julienschmidt/httprouter

for it to work and should be just fine!

  • 写回答

1条回答 默认 最新

  • douhanzhuo6905 2016-09-07 11:12
    关注

    If the pipeline value that you pass to the "content" template execution is dataFinal, then you have to use two {{range}} actions as dataFinal itself is a slice (of type []models.Data), and Data.IData is also a slice (of type []model.User).

    Inside the inner {{range}} you may refer to the User.Name like .Name:

    <li>{{.Name}}</li>
    

    See this working example:

    const templ = `{{define "content"}}
    <h2>THIS IS THE BODY CONTENT</h2>
    
    <ul>
        {{.}}
        {{range .}}
        <ul>
           {{range .IData}}
           <li>{{.Name}}</li>
           {{end}}
        </ul>
        {{end}}
    </ul>
    {{end}}`
    
    // Parsing and executing the template:
    t := template.Must(template.New("").Parse(templ))
    fmt.Println(t.ExecuteTemplate(os.Stdout, "content", dataFinal))
    

    Output (try it on the Go Playground):

    <h2>THIS IS THE BODY CONTENT</h2>
    
    <ul>
        [{content [{jon jon@mail.com}]} {content [{jon jon@mail.com}]}]
    
        <ul>
    
           <li>jon</li>
    
        </ul>
    
        <ul>
    
           <li>jon</li>
    
        </ul>
    
    </ul>
    <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?