3

I'd like to serve some static files from a Snaplet in the Snap framework. How do I do that? The documentation is not exactly clear.

I know how to add routes and stuff, but I'm stuck at two problems:

  1. What would I need to pass to serveDirectory to serve files from the snaplet directory?
  2. How would I reference these static files in Heist templates of my snaplet? I obviously can't use absolute URLs, since I don't know the URL prefix my snaplet is eventually installed in the final application. In other words, how do I get an URL relative to the snaplet root URL in a Heist template?

1 Answers1

2

Yes, serveDirectory is what you would use to serve static files. You might have a route like this:

route [("static", serveDirectory "myDir"), ...]

When you reference those files in templates, you have to use the route that you assigned. So if you had a file myDir/foo.js, then in a template, you'd refer to it with /static/foo.js.

If you don't know your snaplet's base URL, you can get it with the getSnapletRootURL function. Then you can make that available in your templates with a Heist splice.

mightybyte
  • 7,282
  • 3
  • 23
  • 39
  • And what if the snaplet was not nested at `/`, but at `/foo/`? How would I handle that? –  Oct 28 '14 at 12:24
  • If the above route command was inside said snaplet, then the template would need "/foo/static/foo.js". Otherwise, no change. The basic idea is that you should figure out what URL you have to put in your browser (or curl/wget) to get the page, and put that URL in your template. – mightybyte Oct 28 '14 at 13:46
  • Uhm, obviously, but the point is that I **do not know** the exact prefix. It could be anything, and I need to figure it out **dynamically**. –  Oct 28 '14 at 13:59
  • You can use the [getSnapletRootURL](http://hackage.haskell.org/package/snap-0.13.3.1/docs/Snap-Snaplet.html#v:getSnapletRootURL) function and create a splice that makes the information available inside a template. – mightybyte Oct 30 '14 at 16:11