Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a count on html template in Go

Tags:

templates

go

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.

like image 353
jwesonga Avatar asked Dec 31 '12 14:12

jwesonga


People also ask

How to work with templates in go?

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: { {.}}")

How to create a countdown timer in HTML?

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

How to create comment in HTML view file on Golang?

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.

How do you check if a template is valid in HTML?

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.


2 Answers

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)
}
like image 140
jwesonga Avatar answered Oct 06 '22 21:10

jwesonga


Check out the Variables section of text/template

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

range $index, $element := pipeline
like image 40
dskinner Avatar answered Oct 06 '22 20:10

dskinner