go - 打开文件没有那个文件或目录

go - open file no such file or directory

我写了一个包装函数来渲染这样的模板

func RenderTemplate(w http.ResponseWriter, data interface{}, tmpl... string) {
    cwd, _ := os.Getwd()
    for _ , file := range tmpl{
        file = filepath.Join(cwd,"./view/"+file+".html")
    }
    t, err := template.ParseFiles(tmpl...)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    err = t.Execute(w, data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

我在 main

中设置静态文件夹和路由处理程序
http.Handle("/public/",http.StripPrefix("/public/",http.FileServer(http.Dir("public"))))

http.HandleFunc("/",route.IndexHandler)

这是我的路由处理程序

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    files:=[]string{"base","index"}
    util.RenderTemplate(w, nil, files...)
}

我打算使用模板嵌套来帮助 index.html 扩展 base.html

这是base.html

{{define "base"}}
<!DOCTYPE html>
<html>
<head>
    <meta charget="utf-8">
    <title>{{template "title".}}</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="/js/isotope.pkgd.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
    {{template "index".}}
</body>
</html>
{{end}}

这是index.html

<!DOCTYPE html>
<html>
{{define "title"}}Homepage{{end}}
<body>
    {{define "index"}}
    <div class="wrapper">
        <div class="page-content">
            <div class="container">
                <div class="left">
                    <img src="../public/images/img_landing_page_mac.png">
                </div>
                <div class="right">
                    <h2 style="font-size: 33px; letter-spacing: 5px">Organize <br>Modern Knowledge<br> for Mankind</h2>
                    <p style="font-size: 20px;margin-top: 35px;letter-spacing: 4px">Consume, Colect and Revisit <br>Knowledge at Your Fingertips</p>
                    <a href="#" style="margin-top: 80px;display: inline-block;margin-left: -17px"><img src="../public/images/btn_get_chrome.png"></a>
                </div>
            </div>
        </div>
    </div>
    {{end}}
</body>
</html>

但是当我运行服务器,并在浏览器上请求路径时,它显示错误

open base: no such file or directory

我的渲染函数有问题吗?

t, err := template.ParseFiles(tmpl...)

我猜 `tmpl' 似乎不是文件路径:(
我猜你会喜欢这个。

files := make([]string, len(tmpl))
for i, file := range tmpl{
    files[i] = appendfilepath.Join(cwd,"./view/"+file+".html")
}
t, err := template.ParseFiles(files...)