模板变量无法在所有地方解析

huangapple go评论67阅读模式
英文:

Template variable not resolving everywhere

问题

我正在使用Golang模板构建一个网站,并需要在页脚模板中显示一些文本。这是一个在header.html和index.html中解析的变量。

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

type Data struct {
	Title       string
	Field1      string
	Field2      template.HTML
	FooterField string
}

var tmpl *template.Template

func main() {
	router := mux.NewRouter()

	port := ":8085"
	data := Data{}
	data.Title = "Title"
	data.FooterField = "This text does not appear in the footer template"

	router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		err := tmpl.ExecuteTemplate(w, "index", data)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	var err error
	tmpl, err = template.ParseGlob("views/*")
	if err != nil {
		panic(err.Error())
	}

	router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
	})

	fmt.Println("Server running on localhost" + port)

	err = http.ListenAndServe(port, handlers.CompressHandler(router))
	if err != nil {
		log.Fatal(err)
	}
}

在./views文件夹中有header.html:

{{define "header"}}<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{{.Title}}</title></head><body><h1>Header template</h1><div>{{.FooterField}}</div>{{end}}

index.html:

{{define "index"}}{{template "header" . }}
<h1>Index template</h1>
<div>{{.FooterField}}</div>
{{template "footer"}}{{end}}

footer.html:

{{define "footer"}}<h1>Footer template</h1>
Missing FooterField->{{.FooterField}}</body></html>{{end}}

最后,在浏览器上打开http://localhost:8085/,输出应该是:

Header template
This text does not appear in the footer template
Index template
This text does not appear in the footer template
Footer template
Missing FooterField->

这段代码应该可以通过复制粘贴来重现。

你有什么问题吗?

英文:

I am building a website using Golang templates and needed to display some text in the footer template. It's a variable that resolves in header.html and index.html.

package main

import (
	&quot;fmt&quot;
	&quot;html/template&quot;
	&quot;log&quot;
	&quot;net/http&quot;

	&quot;github.com/gorilla/handlers&quot;
	&quot;github.com/gorilla/mux&quot;
)

type Data struct {
	Title string
	Field1 string
	Field2 template.HTML
	FooterField string
}

var tmpl *template.Template

func main() {
	router := mux.NewRouter()

	port := &quot;:8085&quot;
	data := Data{}
	data.Title = &quot;Title&quot;
	data.FooterField = &quot;This text does not appear in the footer template&quot;

	router.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {
		err := tmpl.ExecuteTemplate(w, &quot;index&quot;, data)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	var err error
	tmpl, err = template.ParseGlob(&quot;views/*&quot;)
	if err != nil {
		panic(err.Error())
	}

	router.PathPrefix(&quot;/&quot;).HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		http.FileServer(http.Dir(&quot;./static/&quot;)).ServeHTTP(res, req)
	})

	fmt.Println(&quot;Server running on localhost&quot; + port)

	err = http.ListenAndServe(port, handlers.CompressHandler(router))
	if err != nil {
		log.Fatal(err)
	}
}

And in the ./views I have header.html

{{define &quot;header&quot;}}&lt;!doctype html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;title&gt;{{.Title}}&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Header template&lt;/h1&gt;&lt;div&gt;{{.FooterField}}&lt;/div&gt;{{end}}

index.html

{{define &quot;index&quot;}}{{template &quot;header&quot; . }}
&lt;h1&gt;Index template&lt;/h1&gt;
&lt;div&gt;{{.FooterField}}&lt;/div&gt;
{{template &quot;footer&quot;}}{{end}}

footer.html

{{define &quot;footer&quot;}}&lt;h1&gt;Footer template&lt;/h1&gt;
Missing FooterField-&gt;{{.FooterField}}&lt;/body&gt;&lt;/html&gt;{{end}}

And finally the output in the browser on http://localhost:8085/

Header template
This text does not appear in the footer template
Index template
This text does not appear in the footer template
Footer template
Missing FooterField-&gt;

This code should be able to be reproduced simply by copying and pasting.

Any clue to what my issue is?

答案1

得分: 3

你没有向页脚模板传递任何内容。但是你将 . 传递给了页眉模板,所以你只能在那里看到 .FooterField 的值。

index.html 中将其更改为:{{template "footer" . }}

英文:

you are not passing anything to the footer template. But you pass . to the header template, so you see the value of .FooterField only there.

In index.html change it to: {{template &quot;footer&quot; . }}

huangapple
  • 本文由 发表于 2021年11月7日 03:58:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69867454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定