go - 打开文件没有这样的文件或目录

时间:2016-03-10 00:22:55

标签: html file go render template-engine

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

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

我的渲染功能出了什么问题?

1 个答案:

答案 0 :(得分:1)

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

我想`tmpl&#39;似乎不是文件路径:(
我想你想要这样。

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