谷歌Go模板的Web开发与二维数组



我有一个二维数组的结构体示例:

type Foo struct{testArray[9][9] int}

我想通过模板访问它。

例如

:tmpl.Execute(w, foo)//foo是指向foo结构体的指针,w是解析后的html站点

如何访问模板中的数组?对于使用旧模板包的一维数组,代码如下:

{.repeated section testArray}<p>{@}</p>{.end}

但是二维数组的语法是什么?例如,我必须访问testArray[0][0]

我用新的模板包意外地解决了你的问题。但也许旧的工作原理类似。你有没有试过这样做:

{.repeated section testArray}<p>{.repeated section @}{@} {.end}</p>{.end}

(未测试)无论如何,这是我的解决方案与新的模板包。也许你可以用它:D

package main
import (
    "os"
    "text/template"
)
type Foo struct {
    Data [9][9]int
}
func main() {
    tmpl := template.Must(template.New("example").Parse(`
    <table>
    {{range .Data}}
    <tr>
      {{range .}}<td>{{.}}</td>{{end}}
    </tr>
    {{end}}
    `))
    foo := new(Foo)
    foo.Data[2][1] = 4
    tmpl.Execute(os.Stdout, foo)
}

这个小示例应该会对您有所帮助。

package main
import (
        "net/http"
        "text/template"
)
type Foo struct {
        Array [9][9]int
}
func handler(w http.ResponseWriter, r *http.Request) {
        var foo Foo
        for i := 0; i < len(foo.Array); i++ {
                for j := 0; j < len(foo.Array); j++ {
                        foo.Array[i][j] = j
                }
        }
        tmpl := template.Must(template.New("example").Parse(`
                <html>
                <body>
                <table>
                        {{ $a := .Array }}
                        {{ range $a }}
                        <tr>
                        {{ $elem := . }}
                        {{ range $elem }}
                        {{ printf "<td>%d<td>" . }}
                        {{ end}}
                        </tr>
                        {{end}}
                </table>
                </body>
                </html>
                `))
        tmpl.Execute(w, foo)
}
func main() {
        bindAddress := "127.0.0.1:8080"
        http.HandleFunc("/", handler)
        http.ListenAndServe(bindAddress, nil)
}

最新更新