Samsul Islam
Samsul Islam

Reputation: 2619

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?

Upvotes: 0

Views: 228

Answers (2)

Napoleon Pro
Napoleon Pro

Reputation: 1

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 <p> 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 <script> tag and enter a random number inside our paragraph tag <p>. 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.

Upvotes: 0

Samsul Islam
Samsul Islam

Reputation: 2619

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

Upvotes: 1

Related Questions