在Go中显示html模板的计数

jwe*_*nga 7 templates go

在Go中使用html/templates可以执行以下操作:

<table class="table table-striped table-hover" id="todolist">
    {{$i:=1}}
    {{range .}}         
    <tr>
        <td><a href="id/{{.Id}}">{{$i}}</a></td>
        <td>{{.Title}}</td>
        <td>{{.Description}}</td>
        </tr>
        {{$i++}}

    {{end}}
</table>
Run Code Online (Sandbox Code Playgroud)

每次我添加$ i变量时,应用程序崩溃.

jwe*_*nga 13

在我的html模板中:

<table class="table table-striped table-hover" id="todolist">
        {{range $index, $results := .}}         
        <tr>
            <td>{{add $index 1}}</td>
            <td>{{.Title}}</td>
            <td>{{.Description}}</td>
            </tr>
        {{end}}
    </table>
Run Code Online (Sandbox Code Playgroud)

在go代码中我编写了一个函数,我将其传递给FuncMap:

func add(x, y int) int {
    return x + y
}
Run Code Online (Sandbox Code Playgroud)

在我的经纪人:

type ToDo struct {
    Id          int
    Title       string
    Description string
}

func IndexHandler(writer http.ResponseWriter, request *http.Request) {
    results := []ToDo{ToDo{5323, "foo", "bar"}, ToDo{632, "foo", "bar"}}
    funcs := template.FuncMap{"add": add} 
  temp := template.Must(template.New("index.html").Funcs(funcs).ParseFiles(templateDir + "/index.html"))
    temp.Execute(writer, results)
}
Run Code Online (Sandbox Code Playgroud)


dsk*_*ner 9

看看Variables部分text/template

http://golang.org/pkg/text/template/

range $index, $element := pipeline
Run Code Online (Sandbox Code Playgroud)

  • `html/template`只是在将值传递给`text/template`之前将其转义.如果你查看`html/template`的文档,你会发现它们只是引用你的文本`text/template`. (5认同)