英文:
Golang template serving css on different directory levels
问题
我正在使用golang的"html/template"包来使用_base.html作为框架在多个页面上提供内容。我将多个HTML文件(_base.html和内容文件)合并为一个来提供服务。
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/blog/", blogHandler)
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("http/css"))))
http.ListenAndServe(":1337", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
index := template.Must(template.ParseFiles(
"http/html/_base.html",
"http/html/index.html",
))
index.Execute(w, nil)
}
func blogHandler(w http.ResponseWriter, r *http.Request) {
blog := template.Must(template.ParseFiles(
"http/html/_base.html",
"http/html/blog.html",
))
blog.Execute(w, nil)
}
在我的Web服务器根目录上这样做时,我的CSS可以正常渲染,因为_base.html中的HTML链接标签指向正确的目录,如下所示:
<link href="css/style.css" rel="stylesheet">
然而,当我从/导航到/blog/时,我的CSS向下移动了一个级别(或者可以说我向上移动了一个级别),因此CSS的href突然指向/blog/css/style.css,因此无法渲染。
可以通过在我与_base.html合并的每个内容文件中指定CSS的级别来轻松解决此问题,但是我觉得还应该有另一种更清晰、不同的方法。在这种情况下,是否存在这样的方法,或者我的直觉判断错误?
英文:
I'm using golang's "html/template" package to serve content on multiple pages using the same _base.html as a framework. I merge multiple html files (_base.html and the content file) to serve as one.
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/blog/", blogHandler)
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("http/css"))))
http.ListenAndServe(":1337", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
index := template.Must(template.ParseFiles(
"http/html/_base.html",
"http/html/index.html",
))
index.Execute(w, nil)
}
func blogHandler(w http.ResponseWriter, r *http.Request) {
blog := template.Must(template.ParseFiles(
"http/html/_base.html",
"http/html/blog.html",
))
blog.Execute(w, nil)
}
Doing so on the root of my webserver my css renders just fine, because the html link tag to my .css in _base.html points to the right directory using:
<link href="css/style.css" rel="stylesheet">
however when I navigate from / to /blog/ my css went a level down (or I went a level up, however you'd like to see it) and so the css href suddenly points to /blog/css/style.css and thus it won't render.
This can be easily fixed stating the level of the css in every content-file I merge with _base.html, however I feel there has to be another, cleaner, different way. Is there or is my gut misjudging in this case?
答案1
得分: 9
将
<link href="css/style.css" rel="stylesheet">
改为
<link href="/css/style.css" rel="stylesheet">
我没有测试过,所以不太确定,但是这样修改应该可以。
英文:
Didn't test it, so I'm not really sure, but what about changing
<link href="css/style.css" rel="stylesheet">
to
<link href="/css/style.css" rel="stylesheet">
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论