英文:
Go Web Page Template served Blank
问题
我用Go语言编写了以下代码,用于通过Go程序传递模板和参数值来提供网页:
// +build
package main
import (
"html/template"
"io/ioutil"
"net/http"
)
type Blog struct {
title string
heading string
para string
}
func loadfile(filename string) (string, error) {
byte, err := ioutil.ReadFile(filename)
return string(byte), err
}
func handler(w http.ResponseWriter, r *http.Request) {
blog := Blog{title: "GoLang", heading: "WebServer", para: "coding"}
t, err := template.ParseFiles("test.html")
fmt.Println(err)
t.Execute(w, blog)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":9000", nil)
}
HTML模板文件名为test.html,内容如下:
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
<h1>{{.heading}}</h1>
<p>{{.para}}</p>
</body>
</html>
当我执行该程序时,页面显示为空白。应该传递给模板的参数没有显示在渲染的页面上。我甚至打印了错误,但没有错误信息显示。
英文:
I wrote this Go Lang code for serving web page with template and values passed to parameters through Go program
// +build
package main
import (
"html/template"
"io/ioutil"
"net/http"
)
type Blog struct {
title string
heading string
para string
}
func loadfile(filename string) (string, error) {
byte, err := ioutil.ReadFile(filename)
return string(byte), err
}
func handler(w http.ResponseWriter, r *http.Request) {
blog := Blog{title: "GoLang", heading: "WebServer", para: "coding"}
t, err := template.ParseFiles("test.html")
fmt.Println(err)
t.Execute(w, blog)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":9000", nil)
}
HTML Template file named as test.html as follows
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
<h1>{{.heading}}</h1>
<p>{{.para}}</p>
</body>
</html>
When I execute the program, the issue is that the page served is coming up as blank. The parameters that were to be passed to the template don't show up on the page rendered. I even printed the error but there is no error
答案1
得分: 2
你应该将Blog
结构体的字段的首字母大写,以使它们变为公共字段。
type Blog struct {
Title string
Heading string
Para string
}
此外,你可以将一个map传递给Execute()
方法,就像这样:
b := map[string]string{
"title": "GoLang",
"heading": "WebServer",
"para": "coding",
}
t.Execute(w, b)
英文:
You should write the first letter of the fields of Blog
with upper case to make them public
type Blog struct {
Title string
Heading string
Para string
}
Also you can pass a map to the method Execute()
, something like this:
b := map[string]string{
"title": "GoLang",
"heading": "WebServer",
"para": "coding",
}
t.Execute(w, b)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论