How to use static files on rocket.rs

I'm trying to learn rocket.rs and create a simple app which render a index.html and statics files.
below is a sketch for the beginning, but I'm having problems with the static css and js files that are not identified, by default rocket read a folder in the root directory called templates, I created this folder, put a file index.html.hbs and works, but it doesn't read the js and css files created within the templates/static/js and css folder, is there any way for this to work without using other libs, just the two I'm using

use rocket::{get, launch, routes};
use rocket_dyn_templates::{Template, context};

#[get("/")]
fn index() -> Template {
    Template::render("index", context! {
        foo: 123,
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        .attach(Template::fairing())
}

You could host your static files separately from your templates with rocket::fs::FileServer.

1 Like

As @jofas said, FileServer would probably be the easiest solution.

use rocket::fs::FileServer;

...
#[launch]
fn launcher() -> _ {
    rocket::build()
        ...
        .mount("/assets", FileServer::from("/assets"))
}

Now you can access the files with something like <script src='/assets/js/custom.js'></script>. Note that the assets folder should be at the root of the project (on the same level as the Cargo.toml file), not in the templates folder.

1 Like

Thank you my friends, I managed to think of it

use rocket::{get, launch, routes};
use rocket::fs::{FileServer, relative};
use rocket_dyn_templates::{Template, context};

#[get("/")]
fn index() -> Template {
    Template::render("index", context! {
        foo: 123,
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        .mount("/static", FileServer::from(relative!("templates/static")))
        .attach(Template::fairing())
}

and in the HTML file the path to call was

<script src="/static/js/script.js"></script>

@crazydump I think that it is, generally, bad practice to keep static files like css and js inside the templates folder. The template folder is reserved for templates. Also, it makes it easier to understand for other people taking a look at your code.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.