Suyog
Suyog

Reputation: 341

GO templates for dynamic html

Can anyone please tell me how to code up simple page like guestbook.jsp on https://developers.google.com/appengine/docs/java/gettingstarted/usingjsps using GO templates?

In my opinion it is easy to write one that works but I would like to know if it can be done as concisely as a JSP page.

There are two problems that I don't know how to address

  1. JSP page uses two objects user and request while template creation takes only one.
  2. If we use separate templates for generating a sign-out link and a guestbook, then how do we nest them in the main page?

Upvotes: 0

Views: 3583

Answers (1)

yngling
yngling

Reputation: 1456

What I do is create a struct (that I call a "page" object), populate it with the entities I need, and then operate on them in the template.

func myPage(w http.ResponseWriter, r *http.Request) {
    var user *User // fetch from somewhere

    page := struct {        
        Title     string
        User      *User
    }{"My title", user}

    return templates.ExecuteTemplate(w, "myPage", page)
}

The template can look something like this, giving you access to all fields in the struct:

{{define "myPage"}}
{{template "head" .}}

Title: {{.Title}}<br />
Name: {{.User.Name}}<br />

{{template "tail" .}}
{{end}}

(Note that {{template "head" .}} will include another template, here a header and a footer.)

Another thing I use a lot are variables in the templates. You can define variables by using the dollar symbol.

The following example is not very elegant, but may give you an idea of what is possible. Imagine we have three slices: one with "User" objects, one with "Spot" objects and one with "Checkin" objects. They are all the same length and are related by position (index 0 for each contains the user that was checked in, the spot he/she checked in at, and the checkin object contains the time it happened). "range" will give you two variables as it iterates over the slice: index ($i in the example) and the value ($v). Using "index" you can ask for an entity in a slice, so {{$user := index $checkinUsers $i}} will give you the object at the position pointed to by $i.

{{$checkinUsers := .CheckinUsers}}
{{$checkinSpots := .CheckinSpots}}
{{range $i, $v := .Checkins}}
    {{$user := index $checkinUsers $i}}
    {{$spot := index $checkinSpots $i}}
    <tr>
        <td>
            {{$user.FirstName}} {{$user.LastName}} @ {{$spot.Description}} ({{$v.Time}})<br />
        </td>
    </tr>
    {{end}}

Again, this example isn't very elegant, but I hope you can see that it is possible to make dynamic HTML in Go just as easily as in JSPs (my experience is that the resulting pages are cleaner than JSPs, and thus more understandable by less experienced web-developers and designers).

Ex animo, /Alexander Yngling.

Upvotes: 11

Related Questions