Помогите мне, пожалуйста. У меня есть тип со структурой
type myType struct {
ID string
Name
Test
}
И иметь массив типа
var List []MyType;
Как я могу распечатать в шаблоне свой список со всеми полями структуры?
Благодарю вас!
Помогите мне, пожалуйста. У меня есть тип со структурой
type myType struct {
ID string
Name
Test
}
И иметь массив типа
var List []MyType;
Как я могу распечатать в шаблоне свой список со всеми полями структуры?
Благодарю вас!
Используйте 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-
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)
print in template
? - person David Guan   schedule 02.07.2016