英文:
CSS and images from a different folder are not read when rendering template using Golang
问题
我正在尝试使用Golang的html/template模块渲染模板。但是只有与我正在渲染的页面位于同一文件夹中的CSS文件和图像会被执行,位于不同文件夹中的文件会被忽略。以下是我的代码:
func render(w http.ResponseWriter, filename string, data interface{}) {
tmpl, err := template.ParseFiles(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
例如,对于这个页面:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Start Connect</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="one-page.css" rel="stylesheet">
</head>
one-page.css会被执行,但bootstrap不会被执行。
英文:
I am trying to render a template using the html/template module of Golang. But only CSS files and images from the same folder as the page i am rendering are executed, those located in a different folder are ignored. Here is my code:
func render(w http.ResponseWriter, filename string, data interface{}) {
tmpl, err := template.ParseFiles(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
For this page for example:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Start Connect</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="one-page.css" rel="stylesheet">
</head>
The one-page.css is executed but not the bootstrap.
答案1
得分: 2
在Web上使用../css
应该避免,很可能是你的错误来源。你的Go服务器很可能无法解析该文件(因为你没有处理../css
URI的处理程序)。
所以你应该将../css
部分改为/css
,并告诉你的服务器(你没有提供详细信息,所以我无法给你展示代码)通过提供文件来处理/css
URI。
假设你正在使用默认的net/http
mux,你的代码应该类似于:
mux := http.NewServeMux()
mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
http.ListenAndServe(":8080", mux)
英文:
Using ../css
on the web should be avoided and likely is your error source. Your go server likely cannot resolve the file (because you don't have a handler for the ../css
URI).
So you should change the ../css
part to /css
and tell your server (you didn't provide details, so I cannot show you code) to handle /css
URIs by serving the files.
Assuming that you are using the default net/http
mux, your code should look something like:
mux := http.NewServeMux()
mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
http.ListenAndServe(":8080", mux)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论