Nested ranges in Golang template

huangapple go评论80阅读模式
英文:

Nested ranges in Golang template

问题

我对此还不太熟悉,所以我需要一点帮助。

我有两个这样的结构体:

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

type Student struct {
    ID   string
    Name string
}

我需要做的是,当我从第一个选择元素中选择一个学校对象时,第二个选择元素只显示所选学校的学生。学校对象数组正确显示了所有数据。

<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>
        {{end}}
    </select>
</div>

我需要在第二个选择元素中使用类似于selectedSchoolObject.Students的范围。

提前感谢!

英文:

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!

答案1

得分: 2

Go模板在服务器端(Go应用程序中)执行和渲染。

当您在学校下拉列表中选择某个选项时,这是在浏览器端(客户端)发生的。

浏览器无法执行Go模板。因此,您基本上有两个选择:

1)当用户更改学校下拉列表的选择时,重新渲染页面。这涉及发送一个新的HTTP请求,例如,您可以在URL参数中提供所选学校的ID,并且Go模板可以仅渲染第二个下拉列表中所选学校的学生。

2)您可以在客户端使用JavaScript代码来实现此功能。为此,您需要在渲染的HTML页面中包含所有学校的所有学生,例如在JavaScript数组中,并使用JavaScript代码来更改学生下拉列表的内容。

阅读相关问题:

https://stackoverflow.com/questions/28751637/referencing-go-array-in-javascript/28753476#28753476

https://stackoverflow.com/questions/41197376/interactive-web-pages-in-go/41198615#41198615

https://stackoverflow.com/questions/37118281/dynamically-refresh-a-part-of-the-template-when-a-variable-is-updated-golang/37119014#37119014

https://stackoverflow.com/questions/41136000/creating-load-more-button-in-golang-with-templates/41138344#41138344

英文:

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:

https://stackoverflow.com/questions/28751637/referencing-go-array-in-javascript/28753476#28753476

https://stackoverflow.com/questions/41197376/interactive-web-pages-in-go/41198615#41198615

https://stackoverflow.com/questions/37118281/dynamically-refresh-a-part-of-the-template-when-a-variable-is-updated-golang/37119014#37119014

https://stackoverflow.com/questions/41136000/creating-load-more-button-in-golang-with-templates/41138344#41138344

答案2

得分: 2

我已经使用JavaScript在客户端解决了这个问题。

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		var school = {};
		var schoolsArray = [];
		{{range .Schools}}
			school.ID = {{.ID}};
			school.Name = {{.Name}};
			school.Students = {{.Students}};
			schoolsArray.push(school);
		{{end}}

		$("#school").change(function() {
			var parent = $(this).val();
			Object.keys(schoolsArray).forEach(function (key) {
				if (schoolsArray[key]['ID'] === parent) {
					var students = schoolsArray[key]['Students'];
					listStudents(students);
				}
			});
		});
		function listStudents(students) {
			Object.keys(students).forEach(function (key) {
				$('#student').append($('<option>', {
					value: students[key]['ID'],
					text : students[key]['Name']
				}));
			});
		} </script>

这是我的HTML代码:

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

希望这对其他人也有帮助。欢迎提出改进这段代码的任何建议。

<details>
<summary>英文:</summary>

I have solved this using Javascript on client side. 

    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; &gt;
    	$(document).ready(function() {
    		var school = {};
    		var schoolsArray = [];
    		{{range .Schools}}
    			school.ID = {{.ID}};
    			school.Name = {{.Name}};
    			school.Students = {{.Students}};
    			schoolsArray.push(school);
    		{{end}}
    
    		$(&quot;#school&quot;).change(function() {
    			var parent = $(this).val();
    			Object.keys(schoolsArray).forEach(function (key) {
    				if (schoolsArray[key][&#39;ID&#39;] === parent) {
    					var students = schoolsArray[key][&#39;Students&#39;];
    					listStudents(students);
    				}
    			});
            });
    		function listStudents(students) {
    			Object.keys(students).forEach(function (key) {
    				$(&#39;#student&#39;).append($(&#39;&lt;option&gt;&#39;, {
    					value: students[key][&#39;ID&#39;],
    					text : students[key][&#39;Name&#39;]
    				}));
    			});
    		} &lt;/script&gt;

And this is my HTML code: 



    &lt;div&gt;
      &lt;select name=&quot;school&quot; id=&quot;school&quot;&gt;
          {{range .Schools}}
              &lt;option value=&quot;{{.ID}}&quot;&gt;{{.Name}}&lt;/option&gt;
          {{end}}
      &lt;/select&gt;
    &lt;/div&gt;   &lt;div&gt;
      &lt;select name=&quot;student&quot; id=&quot;student&quot;&gt;
           &lt;/select&gt;
    &lt;/div&gt;



Hope this will be helpful for someone else as well. Also, any suggestions for improving this code is welcome.

</details>



huangapple
  • 本文由 发表于 2017年6月27日 20:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/44780166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定