GoLang HTML模板从模板调用下方删除所有数据 [英] GoLang HTML Templates Removing All Data From Below The Template Call

查看:182
本文介绍了GoLang HTML模板从模板调用下方删除所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是html页面

  {{defineTopPicks }} 
{{templateheader。}}
< div class =content>
{{range .TopPIcks.Results}}
{{end}}
< / div> //下面这个div
{{templatefooter。}}
{{end}}

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

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

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

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



<$ p $
{{definebody}}
< ul>
{code $ t,err:= template.New(TopPicks {$ ImgUrl:=http://image.tmdb.org/t/p/w185}}
{{范围$电影:=。结果}}
< li> {{$ ImgUrl}} {{$ movies.PosterPath}}< / li>
< li> {{$ movie.Adult}}< / li>
< li> {{概述}}< / li>
< li> {{$ movies.ReleaseDate}}< / li>
< li> {{$ movies.GenreIds}}< / li>
< li> {{$ movie.Id}}< / li>
< li> {{$ movie.OriginalTitle}}< / li> $ {b $ b $ lt; li> { $ movies.BackdropPath}}< / li>
< li> {{$ movies.Popularity}}< / li>
< li> {{$ movies.VoteCount}}< /锂>
< li> {{$ movies.Video}}< / li>
< li> {{$ movies.VoteAverage}}< / li>
{{end}}
< / ul>
{{end}}
`)
err = t.ExecuteTemplate(w,body,p)//写入客户端响应


解决方案

你能否看到像这样的东西适合你。我不得不使用不同的网址来获得json结果,但我希望总体大纲能够帮助您解决问题。编辑:忘记信贷代码调用其余API - 约瑟夫Misiti https://github.com/josephmisiti/

 包主

导入(
编码/ json
fmt
io / ioutil
net / http
text / template


类型站结构{
Id int64`json:id`
StationName字符串`json:stationName`
AvailableDocks int64`json:availableDocks`
TotalDocks int64` json:totalDocks`
纬度float64`json:纬度`
经度float64`json:经度
StatusValue字符串`json:statusValue`
StatusKey int64`json:statusKey`
AvailableBikes int64`json:availableBikes`
StAddress1 string`json:stAddress1`
StAddr ess2字符串`json:stAddress2`
城市字符串`json:city`
PostalCode字符串`json:postalCode`
位置字符串`json:location`
高度字符串`json:高度
TestMark bool`json:testStation`
LastCommunicationTime字符串`json:lastCommunicationTime
LandMark字符串`json:landMark
}

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

类型页面struct {
标题字符串
StationsResult stationsResponse
}

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

模板:= template.New(template)
templates.New(Body)。Parse(doc)
templates.New(List)。Parse(docList)

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

page:= page {标题:我的标题,StationsResult:* stations}
templates.Lookup(Body)。Execute(w, ():




$ b函数getStations()(*:






$ b站点响应,错误){

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

func makeRequest(url string)([ ]字节,错误){

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

推迟res.Body.Close()

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

re转] [] 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模板< / h1>
{{templateList.StationsResult}}
< / body>
< / html>
`


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

解决方案

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>
`

这篇关于GoLang HTML模板从模板调用下方删除所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆