简体   繁体   中英

Golang HTML Template Nested Range Loop

type Info struct {
    ID           int      `json:"id"`
    RevCusRat    []string `json:"revcusrat"`
    RevCusCom    []string `json:"revcuscom"`
}

I made a template below, the data is coming, but I need to nest the range loop.

{{ range $revCom := .RevCusCom}}
      <div class="col-12">
          <textarea> {{$revCom}} </textarea>
      </div>
{{end}}
                
{{ range $revRtg := .RevCusRat}}
      <div class="col-3">
          <textarea> {{$revRtg}} </textarea>
      </div>
{{end}}

Can I make it like this? (I tried but does not work. how can I do this in different ways?) I want one comment and one rating to come in order on HTML page.

{{ range $revCom := .RevCusCom}}
     {{ range $revRtg := .RevCusRat}}
         <div class="col-12">
            <textarea> {{$revCom}} </textarea>
            <textarea> {{$revRtg}} </textarea>
         </div>
      {{end}}
{{end}}

The way you are doing it, you'll print all revRtg for each revCom . If that's really what you need to do:

{{ range $revRtg := $.RevCusRat}}

so you can access the .RevCusRat in the outer scope.

However, if you want to print the revRgt matching the revCom :

{{ range $index,$revCom := .RevCusCom}}
    <div class="col-12">
        <textarea> {{$revCom}} </textarea>
        <textarea> {{index $.RevCusRat $index}} </textarea>
    </div>
{{end}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM