错误:未定义:”html/template”.ParseFile

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

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

http://golang.org/pkg/html/template/#ParseFiles

huangapple
  • 本文由 发表于 2015年6月14日 03:41:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/30822799.html
匿名

发表评论

匿名网友

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

确定