Golang HTML模板嵌套循环

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

Golang HTML Template Nested Range Loop

问题

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

我在下面创建了一个模板,数据已经传入,但我需要嵌套循环。

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

我可以这样做吗?(我尝试过,但不起作用。有什么其他方法可以实现这个?)我希望评论和评分按顺序显示在HTML页面上。

{{ range $revCom := .RevCusCom}}
     {{ range $revRtg := .RevCusRat}}
         <div class="col-12">
            <textarea> {{$revCom}} </textarea>
            <textarea> {{$revRtg}} </textarea>
         </div>
      {{end}}
{{end}}
英文:
type Info struct {
	ID           int      `json:&quot;id&quot;`
	RevCusRat    []string `json:&quot;revcusrat&quot;`
	RevCusCom    []string `json:&quot;revcuscom&quot;`
}

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

{{ range $revCom := .RevCusCom}}
      &lt;div class=&quot;col-12&quot;&gt;
          &lt;textarea&gt; {{$revCom}} &lt;/textarea&gt;
      &lt;/div&gt;
{{end}}
                
{{ range $revRtg := .RevCusRat}}
      &lt;div class=&quot;col-3&quot;&gt;
          &lt;textarea&gt; {{$revRtg}} &lt;/textarea&gt;
      &lt;/div&gt;
{{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}}
         &lt;div class=&quot;col-12&quot;&gt;
            &lt;textarea&gt; {{$revCom}} &lt;/textarea&gt;
            &lt;textarea&gt; {{$revRtg}} &lt;/textarea&gt;
         &lt;/div&gt;
      {{end}}
{{end}}

答案1

得分: 3

你正在这样做,你将打印每个revCom的所有revRtg。如果这确实是你需要做的事情:

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

这样你就可以在外部范围内访问.RevCusRat

然而,如果你想打印与revCom匹配的revRgt

{{ range $index,$revCom := .RevCusCom}}
    <div class="col-12">
        <textarea> {{$revCom}} </textarea>
        <textarea> {{index $.RevCusRat $index}} </textarea>
    </div>
{{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}}
    &lt;div class=&quot;col-12&quot;&gt;
        &lt;textarea&gt; {{$revCom}} &lt;/textarea&gt;
        &lt;textarea&gt; {{index $.RevCusRat $index}} &lt;/textarea&gt;
    &lt;/div&gt;
{{end}}

huangapple
  • 本文由 发表于 2021年7月2日 20:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/68225340.html
匿名

发表评论

匿名网友

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

确定