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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里