Search code examples
htmlgogo-templates

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}}

Solution

  • 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}}