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条)

报告相同问题?