doushi3322 2017-06-27 12:20
浏览 122
已采纳

Golang模板中的嵌套范围

I am pretty much new with this, so I need a little bit of help.

I have two structs like this:

type School struct {
    ID          string
    Name        string
    Students    []Student
}

type Student struct {
    ID          string
    Name        string
}

What I need to do is when I select one School object from first select element, that second select element displays only Students from selected School. Array of object School displays all data correctly.

<div>
  <select name="school">
      {{range .Schools}}
          <option value="{{.ID}}">{{.Name}}</option>
      {{end}}
  </select>
</div>   <div>
  <select name="student">
  {{range .Students}}
          <option value="{{.ID}"> {{.Name}}</option>
       </select>
  {{end}}  </div>

I need to range in second select something like selectedSchoolObject.Students.

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • donglang9880 2017-06-27 12:51
    关注

    The Go template is executed and rendered at server side, in / by your Go app.

    When you select something in the School drop-down list, that happens at client side, in the browser.

    The browser cannot execute Go templates. So basically you have 2 options:

    1) When the user changes selection of the Schools drop-down, re-render the page. This involves sending a new HTTP request, you may provide the ID of the selected Scool in a URL parameter for example, and the Go template may render only the Students of the selected school in the 2nd drop-down list.

    2) You may implement this at client side, using JavaScript code. For this, you would need to include all students of all schools in the rendered HTML page, e.g. in JavaScript arrays, and use JavaScript code to change the content of the Students drop-down list.

    Read related questions:

    Referencing Go array in Javascript

    Interactive web pages in Go

    Dynamically refresh a part of the template when a variable is updated golang

    Creating load more button in Golang with templates

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持