在Go中,在HTML模板中显示计数。

huangapple go评论87阅读模式
英文:

Display a count on html template in 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>
英文:

Using html/templates in Go can you do the following:

<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>

every time I add the $i variable the app crashes.

答案1

得分: 17

<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>

func add(x, y int) int {
return x + y
}

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

英文:

In my html template:

&lt;table class=&quot;table table-striped table-hover&quot; id=&quot;todolist&quot;&gt;
	 	{{range $index, $results := .}}			
		&lt;tr&gt;
			&lt;td&gt;{{add $index 1}}&lt;/td&gt;
			&lt;td&gt;{{.Title}}&lt;/td&gt;
			&lt;td&gt;{{.Description}}&lt;/td&gt;
			&lt;/tr&gt;
		{{end}}
	&lt;/table&gt;

In the go code I wrote a function which I passed to the FuncMap:

func add(x, y int) int {
	return x + y
}

In my handler:

type ToDo struct {
	Id          int
	Title       string
	Description string
}

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

答案2

得分: 9

查看text/templateVariables部分

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

range $index, $element := pipeline
英文:

Check out the Variables section of text/template

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

range $index, $element := pipeline

huangapple
  • 本文由 发表于 2012年12月31日 22:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/14102845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定