Search code examples
clojurecompojurering

Serving static resources with relative paths in Clojure to different routes


I'm building off of the lein new compojure-app template. I've got a route to / which works fine, as well as a route to /foo/ that works. Between the two pages, only the body changes, so I would like to stick as much as I can into a common view function (I'm using the default common in views/layout.clj). However, when serving resources by relative path, like css/main.css, my route to / works fine, but the route to /foo/ is looking for /foo/css/main.css instead of looking in the root directory. How do I serve static resources with relative paths to arbitrary routes?


Solution

  • You need to use wrap-base-url middleware along with include-css. The wrap-base-url will set *base-url* dynamic var which will be used to construct URLs for resources included with include-css, include-js or by using to-url directly.

    If you deploy your app as a war in a servlet container, wrap-base-url will autodetect your app root context (e.g. /my-app/). Otherwise you need to provide it the root path manually as the second argument.