Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes. I feel as if <em>not</em> finding a solution comes from not reading the <code>text/template</code> package closely enough. If you are using <code>html/template</code>, the syntax is the same (and they tell you to read text/template ;)). Here is a complete working solution for what you might want to do.</p> <p>Go file:</p> <pre><code>package main import ( "bytes" "io/ioutil" "os" "strconv" "text/template" ) type Foo struct { Id string Name string } type Bar struct { Id string Name string } var foos []Foo var bars []Bar func main() { foos = make([]Foo, 10) bars = make([]Bar, 10) for i := 0; i &lt; 10; i++ { foos[i] = Foo{strconv.Itoa(i), strconv.Itoa(i)} // just random strings bars[i] = Bar{strconv.Itoa(10 * i), strconv.Itoa(10 * i)} } tmpl, err := ioutil.ReadFile("so.tmpl") if err != nil { panic(err) } buffer := bytes.NewBuffer(make([]byte, 0, len(tmpl))) output := template.Must(template.New("FUBAR").Parse(string(tmpl))) output.Execute(buffer, struct { FooSlice []Foo BarSlice []Bar }{ FooSlice: foos, BarSlice: bars, }) outfile, err := os.Create("output.html") if err != nil { panic(err) } defer outfile.Close() outfile.Write(buffer.Bytes()) } </code></pre> <p>Note: You can probably do something to not load the file into an intermediate buffer (use <code>ParseFiles</code>), I just copied and pasted some code that I had written for one of my projects.</p> <p>Template file: </p> <pre><code>{{ $foos := .FooSlice }} {{ $bars := .BarSlice }} {{range $foo := $foos }} &lt;div&gt;Foo {{$foo.Name}}&lt;/div&gt; &lt;div&gt; {{range $bar := $bars}} &lt;div&gt;Bar {{$bar.Name}} &lt;input type="text" name="ids_{{$foo.Id}}_{{$bar.Id}}" /&gt;&lt;/div&gt; {{end}} &lt;/div&gt; {{end}} </code></pre> <p>The two morals of this story are<br> a) use variables in templates judiciously, they are beneficial<br> b) range in templates also can set variables, you do not need to rely solely on <code>$</code> or <code>.</code></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload