Handlebars does not include css

I'm having trouble with including external css in my .hbs template. For some reason it's like the template can't find the css file. I've tried placing it at every parent of the template file.

Project is based on dev-mode example at handlebars-rust/examples at master · sunng87/handlebars-rust · GitHub

Directory layout:

./
|- Cargo.lock
|- Cargo.toml
|- Session.vim
|- src
    |- main.rs
|- target
|- templates
    |- static
        |- index.hbs
        |- styles.css

Rust code:

use std::sync::Arc;
use handlebars::Handlebars;
use serde_json::json;
use warp::{self, Filter};
#[tokio::main]
async fn main() {
    let mut reg = Handlebars::new();
    reg.register_template_file("tpl", "./templates/static/index.hbs").unwrap();
    let hbs = Arc::new(reg);
    let route = warp::get().map(move || {
        let result = hbs
            .render("tpl", &json!({"model": "t14s", "brand": "Thinkpad"}))
            .unwrap_or_else(|e| e.to_string());
        warp::reply::html(result)
    });
    warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
}

Template:

<!DOCTYPE html>
<html>
  <head>
    <title>My Laptop</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <p>My current laptop was {{brand}}: <b>{{model}}</b></p>
  </body>
</html>

CSS:

body {
  background-color: powderblue;
}
h1 {
  color: blue;
}
p {
  color: red;
}

do you have a route to handle the static files? AFAICS you route every request to handlebars, but handlebars does not know about styles.css

I use

let css = warp::path("css").and(warp::fs::dir(format!(
            "{}/css",
            std::env::current_dir().unwrap().display()
        )));

And you put styles.css in ./css (or replace {}/css with {}/templates/static but that will expose other files in that directory too

Thank you very much, this did clear some things up and lead me to further research with a new understanding.

I added a css path like you, and combined the filters with .or:

let css = warp::path("styles").and(warp::fs::dir("static/styles/"));
let route = warp::get().map( /* handlebars templating */ );
let routes = css.or(route);
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;

And moved my css files to a new directory ./static/styles. Also, the .hbs template needs modifying to

<link rel="stylesheet" href="styles/styles.css">
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.