rustrust-axumhtml-templates

How to pass a variable data into the HTML file?


use rand::Rng;

#[derive(Debug, Deserialize, Serialize)]
struct RangeParameters {
    start: usize,
    end: usize
}

async fn handler_random_number_generator(Query(params): Query<RangeParameters>) -> impl IntoResponse{
    let random_number = rand::thread_rng().gen_range(params.start..params.end);
    Html(include_str!("../index.html"))
}

I want to pass the random_number in the index.html file as a value for some a placeholder. Is this possible?


Solution

  • I have achieved this by using the askama crate:

    use rand::Rng;
    
    #[derive(Debug, Deserialize, Serialize)]
    struct RangeParameters {
        start: usize,
        end: usize
    }
    
    #[derive(Template)] // this will generate the code...
    #[template(path = "hello.html")]
    struct RandomNumber {
        random: usize
    }
    
    async fn handler_random_number_generator(Query(params): Query<RangeParameters>) -> impl IntoResponse{
        let random_number = rand::thread_rng().gen_range(params.start..params.end);
        let random = RandomNumber {
            random: random_number
        };
        Html(format!("{}", random.render().unwrap()))
    }