GoLang HTML模板从模板调用下方删除所有数据

时间:2016-03-13 15:45:37

标签: html go

我在html页面中调用了html模板,并且调用下方的所有内容都没有显示在页面上。

这是html页面

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

关闭内容类div后,页脚未显示。当我删除

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

页脚出现在页面底部,html被注入页面底部,但我无法控制它的放置位置。这是怎么回事?

我正在main.go文件中创建TopPicks模板。

 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

1 个答案:

答案 0 :(得分:0)

你能看出这样的东西是否适合你。我不得不使用不同的网址来获取json结果,但我希望整体大纲可以帮助您解决问题。编辑:忘记给代码打电话给其余的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>
`