Массив структур в шаблонах

Помогите мне, пожалуйста. У меня есть тип со структурой

type myType struct {
    ID string 
    Name
    Test 
}

И иметь массив типа

var List []MyType;

Как я могу распечатать в шаблоне свой список со всеми полями структуры?

Благодарю вас!


person Максим Ткаченко    schedule 02.07.2016    source источник
comment
Что ты имеешь в виду print in template?   -  person David Guan    schedule 02.07.2016
comment
в шаблоне, например: ‹table› {{for i range List }} ‹tr› ‹td›List[i].ID‹/td› ‹td›List[i].Name‹/td› ‹td›List[ i].Test‹/td› ‹/tr› {{end for}} ‹/table›   -  person Максим Ткаченко    schedule 02.07.2016


Ответы (2)


Используйте range и присвоение переменных. См. соответствующие разделы text/template документации. Также см. пример ниже:

package main

import (
    "fmt"
    "os"
    "text/template"
)

type myType struct {
    ID   string
    Name string
    Test string
}

func main() {
    list := []myType{{"id1", "name1", "test1"}, {"i2", "n2", "t2"}}

    tmpl := `
<table>{{range $y, $x := . }}
  <tr>
    <td>{{ $x.ID }}</td>
    <td>{{ $x.Name }}</td>
    <td>{{ $x.Test }}</td>
  </tr>{{end}}
</table>
`

    t := template.Must(template.New("tmpl").Parse(tmpl))

    err := t.Execute(os.Stdout, list)
    if err != nil {
        fmt.Println("executing template:", err)
    }
}

https://play.golang.org/p/W5lRPxD6r-

person Amit Kumar Gupta    schedule 02.07.2016
comment
Используйте html/template всякий раз, когда выводится HTML (он здесь), потому что он защищен от инъекция кода. - person icza; 02.07.2016

Если вы говорите о шаблоне HTML, вот как это будет выглядеть:

{{range $idx, $item := .List}}
<div>
    {{$item.ID}}
    {{$item.Name}}
    {{$item.Test}}
</div>
{{end}}

И вот как вы передадите этот фрагмент в шаблон.

import (
htpl "html/template"
"io/ioutil"
)

content, err := ioutil.ReadFile("full/path/to/template.html")
if err != nil {
    log.Fatal("Could not read file")
    return
}

tmpl, err := htpl.New("Error-Template").Parse(string(content))
if err != nil {
    log.Fatal("Could not parse template")
}


var html bytes.Buffer
List := []MyType // Is the variable holding the actual slice with all the data
tmpl.Execute(&html, type struct {
    List []MyType
}{
    List
})
fmt.Println(html)
person KBN    schedule 02.07.2016