carllerche / tower-web

A fast, boilerplate free, web framework for Rust
MIT License
981 stars 51 forks source link

Request: Example that showcases linking CSS, JS, etc #132

Closed phrohdoh closed 6 years ago

phrohdoh commented 6 years ago

I have no idea where to place CSS and JS files and how to link them in my hbs files.

Are the paths relative to the templates directory (that lives in the crate root)?

alleyshairu commented 6 years ago

Look at the static_file.rs example.

This is how my setup looks like. I have created a public folder just like template folder and placed my assets (build.css and build.js) there. Then I have an assets resource.

struct AssetsResource;

impl_web! {
    impl AssetsResource {
        #[get("/assets/:name")]
        #[content_type("plain")]
        fn index(&self, name: String) -> impl Future<Item = File, Error = io::Error> {
            let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
            path.push("public");
            path.push(name);
            File::open(path)
        }
    }
}

HTML looks like <link rel="stylesheet" type="text/css" href="/assets/build.css"/>

phrohdoh commented 6 years ago

Thanks @AlleyShairu, I just saw your comment after throwing something similar together.

impl_web! {
    impl Service {
        #[get("/css/*rel_path")]
        #[content_type("text/css")]
        fn get_app_css(&self, rel_path: PathBuf) -> impl Future<Item = File, Error = io::Error> {
            let mut path = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/css"));
            path.push(rel_path);
            File::open(path)
        }
    }
}

Which I then use like so:

<html>
    <head>
        <title>{{ title }}</title>
        <link rel="stylesheet" href="/css/app.css">
    </head>
    <body>
        <div><h1>Winning!</h1></div>
    </body>
</html>