我正在嘗試從目錄加載 html 文件,但收到錯誤“打開模板:沒有這樣的文件或目錄”我的目錄結構如下/Users/{username}/go/src/app main.go/Users/{username}/go/src/app/templates mytemplate.html錯誤來自下面的行template.Must(template.ParseFiles(filepath.Join("templates", "mytemplate.html")))我是新手,只是想感受一下語法。編輯 1我正在使用“go build”命令構建項目并從上面顯示的“app”目錄中執行它。$GOROOT = /usr/local/go $GOPATH = /Users/{username}/go我還更新了目錄結構以集成 $GOPATH
2 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
檢查程序在運行時的工作目錄
dir, _ := os.Getwd()
fmt.Println(dir)
然后您可以使用它來獲取模板的正確路徑
template.Must(template.ParseFiles(filepath.Join(dir, "templates", "mytemplate.html")))
對于生產用途,您可以從dir配置文件或環境中獲取 val ,
參考:https : //golang.org/pkg/os/#Getwd
編輯:當您運行程序時,請確保您cd在終端中使用的正確目錄中

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
嘗試這個,
template.Must(template.New("mytemplate.html").ParseFiles("templates/mytemplate.html"))
- 2 回答
- 0 關注
- 230 瀏覽
添加回答
舉報
0/150
提交
取消