How to pass a variable data into the html file

78 views Asked by At
`#[derive(Debug, Deserialize, Serialize)]
struct RangeParameters {
    start: usize,
    end: usize
}
use rand:: Rng;

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. How it is possible. Please help and pardon me for my English.

I want to pass the random_number in the index.html file. where in index.html exists a place holder. In html place holder I want to pass a variable, is this possible? please help.

2

There are 2 answers

0
Samsul Islam On BEST ANSWER

I have achived this by using askama create

Here is my code

struct RangeParameters {
    start: usize,
    end: usize
}

#[derive(Template)] // this will generate the code...
#[template(path = "hello.html")]
struct RandomNumber {
    random: usize
}
use rand:: Rng;

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()))

}
1
Napoleon Pro On

I dont know if this will answer your question fully or partially but one way i can think of doing something like this is by using "DOM Manipulation".

Lets say you have the following HTML simple skeleton code with a simple

tag that you want to insert something inside it and after your string:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<div>
    <p> hello world.  </p>
</div>
    
</body>
</html>

So in the above example we can insert the following lines of code with a simple Javascript script with tag and enter a random number inside our paragraph tag

. Then it becomes as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<div>
    <p> hello world.  </p>
</div>

<script>
    const para = document.querySelector('p');
    console.log("before changing: ");
    console.log(para);
    console.log("after changing: ");
    let var1 = Math.random();
    para.innerText += "\nrandom number inserted is: \n";
    para.innerText += var1;
    console.log(para);
</script>
    
</body>
</html>

If you want to see how this is happening in the background then you can open this html, right click somewhere and click "inspect element" then navigate to the console tab and you can clearly see what is being changed.

Hope this helps a bit.