請幫助我。 我有結構模板中的數組結構
type myType struct {
ID string
Name
Test
}
類型和具有類型
var List []MyType;
的陣列如何,我可以在模板打印我列出了所有結構域?
謝謝!
請幫助我。 我有結構模板中的數組結構
type myType struct {
ID string
Name
Test
}
類型和具有類型
var List []MyType;
的陣列如何,我可以在模板打印我列出了所有結構域?
謝謝!
使用range
和變量賦值。請參閱text/template
documentation的相應部分。另請參見下面的例子:
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)
}
}
謝謝你,阿米爾 –
只要輸出是HTML(在這裏),請使用['html/template'](https://golang.org/pkg/html/template/),因爲它對代碼注入是安全的。 – icza
如果你在談論的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'?在模板 –
等作爲: