html模板中的内容将被模板';s文件位置和不需要的文本
我使用html/template包在提交表单时提供一个模板。正在使用模板文件的位置而不是应替换{{.Title}的文本呈现作为该模板副本的页面 因此,在response.html中,{.Title}显示为“Projects/Go/src/web/site/index”,而不是“I feel that is” 如何将{.Title}替换为文本而不是文件位置 这是我的密码:html模板中的内容将被模板';s文件位置和不需要的文本,html,templates,go,web-frameworks,Html,Templates,Go,Web Frameworks,我使用html/template包在提交表单时提供一个模板。正在使用模板文件的位置而不是应替换{{.Title}的文本呈现作为该模板副本的页面 因此,在response.html中,{.Title}显示为“Projects/Go/src/web/site/index”,而不是“I feel that is” 如何将{.Title}替换为文本而不是文件位置 这是我的密码: package main import ( "fmt" "net/http" "github.c
package main
import (
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"html/template"
"io/ioutil"
)
type Page struct {
Title string
Body []byte
}
func loadPage(title string) (*Page, error){
filename := title + ".html"
body, err := ioutil.ReadFile(filename)
if err != nil{
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page){
t, err := template.ParseFiles(tmpl + ".html")
if err != nil{
panic(err)
}
err = t.Execute(w, p)
fmt.Println(err)
}
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
p = &Page{Title: "I feel that is "}
panic(err)
}
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}
func serveSingle(filename string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
}
}
func main() {
goji.Get("/", serveSingle("Projects/Go/src/web/site/index.html"))
goji.Handle("/ask", response)
goji.Serve()
}
默认情况下,loadPage()
函数将Page.Title
设置为文件路径,减去.html
扩展名
当err!=无
。您还使用p=&Page{Title:“我觉得那是”}
行完全覆盖p
变量,而不是在现有的页面上设置Title
字段
您应该尝试更改:
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
p = &Page{Title: "I feel that is "}
panic(err)
}
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}
致:
loadPage()
函数将页面标题设置为title
变量,该变量在响应的第一行设置为Projects/Go/src/web/site/index
。此外,您只需将title
设置为“I feel that”iferr!=无
。这可能是不对的。尝试将p=&Page{Title:“I feel that”}
行更改为p.Title=“I feel that”
,并将其移到错误检查块之外。@intermernet它比那个字符串更复杂。为了这个问题,我把它说得这么简单。@Intermernet谢谢你指出这一点。这就解决了问题。请你把它贴出来作为答案,这样我可以选择它。
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
panic(err)
}
p.Title = "I feel that is "
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}