英文:
go error: undefined: "html/template".ParseFile
问题
在编译代码时,我遇到了以下错误:
“html/template undefined: "html/template".ParseFile”
错误出现在源代码的这一行:
t, _ := template.ParseFile("edit.html", nil)
以下是代码的翻译版本:
package main
import (
	"net/http"
	"io/ioutil"
	"html/template"
)
type Page struct {
	Title string
	Body  []byte
}
func (p *Page) save() error {
	filename := p.Title + ".txt"
	return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) {
	filename := title + ".txt"
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: body}, nil
}
const lenPath = len("/view/")
func editHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[lenPath:]
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
	}
	t, _ := template.ParseFile("edit.html", nil)
	t.Execute(p, w)
}
func main() {
	http.HandleFunc("/edit/", editHandler)
	http.ListenAndServe(":8080", nil)
}
请帮我解决这个错误。
英文:
I have the following error while compiling the code
"html/template undefined: "html/template".ParseFile"
at the string of the source code "t, _ := template.ParseFile("edit.html", nil)"
package main
import (
	"net/http"		
	"io/ioutil"
	"html/template"
)
		
   	type Page struct {
   		Title string
   		Body  []byte
    	}
    	
   	func (p *Page) save() error {
    		filename := p.Title + ".txt"
    		return ioutil.WriteFile(filename, p.Body, 0600)
   	}
   	
   	func loadPage(title string) (*Page, error) {
   		filename := title + ".txt"
  		body, err := ioutil.ReadFile(filename)
  		if err != nil {
   			return nil, err
   		}
   		return &Page{Title: title, Body: body}, nil
   	}
   	
	const lenPath = len("/view/")
	
	func editHandler(w http.ResponseWriter, r *http.Request) {
		title := r.URL.Path[lenPath:]
		p, err := loadPage(title)
		if err != nil {
			p = &page{title: title}
		}
		t, _ := template.ParseFile("edit.html", nil)
		t.Execute(p, w)
	}
	
   	func main() {
    	http.HandleFunc("/edit/", editHandler)
   		http.ListenAndServe(":8080", nil)
   	}
Help tp remove this error.
答案1
得分: 1
应该是template.ParseFiles("edit.html")。
复数形式而不是单数形式。
http://golang.org/pkg/html/template/#ParseFiles
英文:
It should be template.ParseFiles("edit.html")
plural not singular
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论