Expand description

This section describes how to set up your project to serve static content using ructe.

To do this, the first step is to add a line in build.rs telling ructe to find and transpile your static files:

let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let in_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
compile_static_files(&in_dir.join("static"), &out_dir).unwrap();
compile_templates(&in_dir.join("templates"), &out_dir).unwrap();

Then you need to link to the encoded file. For an image, you probably want to link it from an <img> tag in a template. That can be done like this:

@use super::statics::image_png;
@()
<img alt="Something" src="/static/@image_png.name">

So, what has happened here? First, assuming the static directory in your $CARGO_MANIFEST_DIR contained a file name image.png, your templates::statics module (which is reachable as super::statics from inside a template) will contain a pub static image_png: StaticFile which can be imported and used in both templates and rust code. A StaticFile has a field named name which is a &'static str containing the name with the generated hash, image-SomeHash.png.

The next step is that a browser actually sends a request for /static/image-SomeHash.png and your server needs to deliver it. Here, things depend on your web framework, so we start with some pseudo code, and then goes on to working examples for iron and nickel.

/// A hypothetical web framework calls this each /static/ request,
/// with the name component of the URL as the name argument.
fn serve_static(name: &str) -> HttpResult {
    if let Some(data) = StaticFile::get(name) {
        HttpResult::Ok(data.content)
    } else {
        HttpResult::NotFound
    }
}

The StaticFile::get function returns the &'static StaticFile for a given file name if the file exists. This is a reference to the same struct that we used by the name image_png in the template. Besides the name field (which will be equal to the argument, or get would not have returned this StaticFile), there is a content: &'static [u8] field which contains the actual file data.