2016-07-02 45 views
3

請幫助我。 我有結構模板中的數組結構

type myType struct { 
    ID string 
    Name 
    Test 
} 

類型和具有類型

var List []MyType; 

的陣列如何,我可以在模板打印我列出了所有結構域?

謝謝!

+0

你是什麼意思'print in template'?在模板 –

+0

等作爲:

{{對於i範圍列表}} ​​列表[I] .ID ​​列表[I]請將.Name ​​列表[I]。測試 { {end for}}

回答

1

使用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) 
    } 
} 

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

+0

謝謝你,阿米爾 –

+0

只要輸出是HTML(在這裏),請使用['html/template'](https://golang.org/pkg/html/template/),因爲它對代碼注入是安全的。 – icza

0

如果你在談論的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)