GoLang HTML Templates Removing All Data From Below

2019-09-09 12:19发布

I am calling a html template in my html page and everything below the call is not being shown on the page.

This is the html page

{{define "TopPicks"}}
{{template "header" .}}
<div class="content">       
   {{range .TopPIcks.Results}}
   {{end}}
   </div> // Below this div
{{template "footer" .}}
{{end}}

After the closing content class div the footer is not being displayed. When I remove the

{{range .TopPIcks.Results}}
       {{end}}

The footer appears at the bottom of the page and the html is injected at the bottom of the page but I cannot control where it is placed. What reason is this happening?

I am creating the TopPicks template in the main.go file.

 t, err := template.New("TopPicks").Parse(`
      {{define "body"}}
        <ul>
        {{$ImgUrl := "http://image.tmdb.org/t/p/w185" }}
        {{range $movies := .Results}}
        <li>{{$ImgUrl}}{{$movies.PosterPath}}</li>
        <li>{{$movies.Adult}}</li>
        <li>{{$movies.Overview}}</li>
        <li>{{$movies.ReleaseDate}}</li>
        <li>{{$movies.GenreIds}}</li>
        <li>{{$movies.Id}}</li>
        <li>{{$movies.OriginalTitle}}</li>
        <li>{{$movies.OriginalLanguage}}</li>
        <li>{{$movies.Title}}</li>
        <li>{{$ImgUrl}}{{$movies.BackdropPath}}</li>
        <li>{{$movies.Popularity}}</li>
        <li>{{$movies.VoteCount}}</li>
        <li>{{$movies.Video}}</li>
        <li>{{$movies.VoteAverage}}</li>
        {{end}}
        </ul>
      {{end}}
      `)
    err = t.ExecuteTemplate(w, "body", p) // This writes the client response

标签: html go
1条回答
2楼-- · 2019-09-09 12:45

Can you see if something like this works for you. I had to use a different url to get json results, but I am hoping the overall outline will help you fix your problem. EDIT: Forgot to credit the code for calling the rest api - Joseph Misiti https://github.com/josephmisiti/go-citibike.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "text/template"
)

type station struct {
    Id                    int64   `json:"id"`
    StationName           string  `json:"stationName"`
    AvailableDocks        int64   `json:"availableDocks"`
    TotalDocks            int64   `json:"totalDocks"`
    Latitude              float64 `json:"latitude"`
    Longitude             float64 `json:"longitude"`
    StatusValue           string  `json:"statusValue"`
    StatusKey             int64   `json:"statusKey"`
    AvailableBikes        int64   `json:"availableBikes"`
    StAddress1            string  `json:"stAddress1"`
    StAddress2            string  `json:"stAddress2"`
    City                  string  `json:"city"`
    PostalCode            string  `json:"postalCode"`
    Location              string  `json:"location"`
    Altitude              string  `json:"altitude"`
    TestStation           bool    `json:"testStation"`
    LastCommunicationTime string  `json:"lastCommunicationTime"`
    LandMark              string  `json:"landMark"`
}

type stationsResponse struct {
    ExecutionTime string    `json:"executionTime"`
    StationList   []station `json:"stationBeanList"`
}

type page struct {
    Title          string
    StationsResult stationsResponse
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Header().Add("Content Type", "text/html")

        templates := template.New("template")
        templates.New("Body").Parse(doc)
        templates.New("List").Parse(docList)

        stations, err := getStations()
        if err != nil {
            fmt.Println(err)
        }

        page := page{Title: "My Title", StationsResult: *stations}
        templates.Lookup("Body").Execute(w, page)

    })

    http.ListenAndServe(":8000", nil)
}

func getStations() (*stationsResponse, error) {

    body, err := makeRequest("https://www.citibikenyc.com/stations/json")
    if err != nil {
        return nil, err
    }
    s, err := parseStations(body)
    return s, err
}

func makeRequest(url string) ([]byte, error) {

    res, err := http.Get(url)
    if err != nil {
        return nil, err
    }

    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return nil, err
    }

    return []byte(body), err
}

func parseStations(body []byte) (*stationsResponse, error) {
    var s = new(stationsResponse)
    err := json.Unmarshal(body, &s)
    if err != nil {
        fmt.Println("whoops:", err)
    }

    return s, err
}

const docList = `
<ul >
    {{range .StationList}}
    <li>{{.StationName}}</li>
    {{end}}
</ul>
`

const doc = `
<!DOCTYPE html>
<html>
    <head><title>{{.Title}}</title></head>
    <body>
        <h1>Hello Templates</h1>
        {{template "List" .StationsResult}}
    </body>
</html>
`
查看更多
登录 后发表回答