How to Include Images, CSS, and/or Javascript in Your Sinatra Web Application
Sinatra is a web application library that was designed to make building small or modular web apps easy. It was built in Ruby by Blake Mizerany in 2007 and is used by everyone from junior web devs like myself to big companies like Apple and the BBC.
I found the Sinatra documentation on how to include CSS/ images/ Javascript a bit hard to find. Turns out this topic is covered under the headline “Static Files.” Here’s what it says:
Static Files
Static files are served from the ./public directory. You can specify a different location by setting the:public_folder option:
set :public_folder, File.dirname(__FILE__) + '/static'
Note that the public directory name is not included in the URL. A file ./public/css/style.css is made available as http://example.com/css/style.css.
Use the :static_cache_control setting (see below) to add Cache-Control header info.
So that tells us that Sinatra, by default, looks for things like CSS and Javascript files in a directory called Public. If you want to change where Sinatra looks, use the code above in whatever file you use to start your server.
Assuming you’re OK with going the Public folder route, it’s really simple to add images, CSS or Javascript. Here’s how:
- Add a directory called Public to the root of your app.
- Add additional directories within Public as needed (a folder for your images, one for your stylesheets, one for Javascript). Or, if your app’s really simple, just add images and files directly to the Public folder.
- In the appropriate View file, add a link element to the html head that reflects the path to the CSS or Javascript file. For example, here’s the head from index.erb in an app I am building:
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”/style.css” />
</head>
4. For images, once they are in the Public folder, simply use them as you would normally within your HTML:
<img src=”images/brooklynbridgepostcard.jpg”>
That’s all folks! Happy Sinatra-ing!