猿问

在 GoLang 中将 Json 数据映射到 Html 模板

我正在遍历我的 API 响应并将其添加到这样的 html 模板中,


 // Following sends same information as above to the browser as html

     t, err := template.New("TopMovies").Parse(`

      {{define "TopMovies"}}

        <html>

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

        </html>

      {{end}}

      `)

    err = t.ExecuteTemplate(w, "T", p) // This writes the client response

}

我的印象是我应该能够像这样在我的 html 模板中调用它,


{{.TopMovies}}

但是当我运行应用程序时,数据没有出现在我调用它的 html 页面中。我在这里错过了什么?


我创建了一个这样的结构,


//A Page structure

type Page struct {

  Title string

  TopMovies string

}

然后在 main.go


   http.HandleFunc("/TopPicks", TopMoviesHandler)


TopPicks.html


{{define "TopPicks"}}

    {{template "header" .}}

    <div class="content">

    {{.TopMovies}}

    </div>

     {{template "footer" .}}

    {{end}}

这是什么工作,


func aboutHandler(w http.ResponseWriter, r *http.Request) {

  display(w, "about", &Page{Title: "About"})

}

我可以用与我之前提到的相同的方式向页面添加标题,但使用 display()


并在 html 模板中


<title>{{.Title}}</title>

我怎样才能使我的 json 响应有效?


当年话下
浏览 249回答 2
2回答

慕码人8056858

我想你想要: t.ExecuteTemplate(w, "body", p)话虽如此,如果您只想使用多个模板,您可以通过创建一个主顶级模板,然后将所有部分解析为子模板来实现。这是一个示例(在 Play 上)。轻松更改为遍历文件系统并加载所有模板,然后您只需执行与 http.Request 路径匹配的模板。package mainimport "html/template"import "os"import "log"var mainText = `Normal page stuff{{ template "_header_" . }}{{ template "body" . }}`var bodyText = `&nbsp;Body has: {{ .Thing }}`var headerText = `&nbsp;I am header text`type Stuff struct {&nbsp; &nbsp; Thing string}func main() {&nbsp; &nbsp; t := template.New("everything")&nbsp; &nbsp; // parse all templates you may want&nbsp; &nbsp; template.Must(t.New("/").Parse(mainText))&nbsp; &nbsp; template.Must(t.New("_header_").Parse(headerText))&nbsp; &nbsp; template.Must(t.New("body").Parse(bodyText))&nbsp; &nbsp; if err := t.ExecuteTemplate(os.Stdout, "/", Stuff{"I am a thing"}); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("Failed to execute:", err)&nbsp; &nbsp; }}

互换的青春

好的,我认为原始代码有两个问题。处理程序调用了错误的模板func TopMoviesHandler(w http.ResponseWriter, r *http.Request) { ...snip 原代码...err = t.ExecuteTemplate(w, "T", p) // This writes the client responseShould be&nbsp;err = t.ExecuteTemplate(w, "TopMovies", p) // This writes the client response传递给嵌套模板的上下文不正确在html文件中有这个代码{{define "TopPicks"}}&nbsp; &nbsp; &nbsp;{{template "header" .}}&nbsp; &nbsp; &nbsp;<div class="content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{.TopMovies}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{template "MyTemplate" . }}&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp;{{template "footer" .}}{{end}}哪个应该是{{define "TopPicks"}}&nbsp; &nbsp; &nbsp;{{template "header" .}}&nbsp; &nbsp; &nbsp;<div class="content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{.TopMovies}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{template "MyTemplate" .TopMovies }}&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp;{{template "footer" .}}{{end}}原因是您试图将主上下文传递给嵌套模板,而不是模板期望的 json 结果。原答案我做了一个我认为你需要做的简单例子。在我设置 topMovies 变量的地方,您可以在此处设置 api 调用的结果。我希望这有助于向您展示您需要更好地遵循的顺序。package mainimport (&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "text/template")type movie struct {&nbsp; &nbsp; Title string}type page struct {&nbsp; &nbsp; Title&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; TopMovies []movie}func main() {&nbsp; &nbsp; http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; w.Header().Add("Content Type", "text/html")&nbsp; &nbsp; &nbsp; &nbsp; templates := template.New("template")&nbsp; &nbsp; &nbsp; &nbsp; templates.New("Body").Parse(doc)&nbsp; &nbsp; &nbsp; &nbsp; templates.New("List").Parse(docList)&nbsp; &nbsp; &nbsp; &nbsp; topMovies := []movie{{Title: "Movie 1"}, {Title: "Movie 2"}, {Title: "Movie 3"}}&nbsp; &nbsp; &nbsp; &nbsp; page := page{Title: "My Title", TopMovies: topMovies}&nbsp; &nbsp; &nbsp; &nbsp; templates.Lookup("Body").Execute(w, page)&nbsp; &nbsp; })&nbsp; &nbsp; http.ListenAndServe(":8000", nil)}const docList = `<ul >&nbsp; &nbsp; {{range .}}&nbsp; &nbsp; <li>{{.Title}}</li>&nbsp; &nbsp; {{end}}</ul>`const doc = `<!DOCTYPE html><html>&nbsp; &nbsp; <head><title>{{.Title}}</title></head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <h1>Hello Templates</h1>&nbsp; &nbsp; &nbsp; &nbsp; {{template "List" .TopMovies}}&nbsp; &nbsp; </body></html>`
随时随地看视频慕课网APP

相关分类

Go
我要回答