Golang template serving css on different directory levels
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">
?
Related videos on Youtube
Dani
Updated on June 17, 2022Comments
-
Dani almost 2 years
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?