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.
When we run the above program Go playground link, the output we get is: There are three main stages to working with templates in general that we see in the program above: Create a new Template object: tmpl := template.New ("test") Parse a template string: tmpl, err := tmpl.Parse ("Array contents: { {.}}")
Creating a Countdown Timer Example Display the countdown timer in an element --> <p id="demo"></p> <script> // Set the date we're counting down to
We can use below syntax to create comment in HTML view file on golang – We can check variable existence and display element based on variable value using IF, There following way to add if condition into the golang template – We are checking employee status is active or , if active is true then display active label.
Parsing an HTML template Let’s try parsing an HTML document. Below show codes are used for this example. To verify if a template is valid, we use template.Must () function. It helps verify the template during parsing.
In my html template:
<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>
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, "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)
}
Check out the Variables
section of text/template
http://golang.org/pkg/text/template/
range $index, $element := pipeline
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With