Embedding Rust in HTML

Hi, I wonder if I could get help as always please?
I wonder if I can display the value of a Rust variable whilst inside HTML code (either on a html page or inside rust's code i.e. inside actix-web's .body).

So, I have the following function that works fine to simply render the value of 't' on the webpage:

async fn process_values(form: web::Form<ProcessFormData>) -> Result<HttpResponse> { 
    let t = form.voltage*2; 
    Ok(HttpResponse::Ok().content_type("text/plain").body(format!("The result is: {}", t)))
}

but I want to have other HTML tags too along with displaying the value of 't' like this:

async fn process_values(form: web::Form<ProcessFormData>) -> Result<HttpResponse>  { 
    let t = form.voltage*2;
    Ok(HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body("<h2>The result is: </h2> t "))
}

so how can I access the value of 't' inside HTML?
Many thanks

Does this work?

.body(format!("<h2>The result is: </h2> {} ", t))

(or with the new println syntax)

.body(format!("<h2>The result is: </h2> {t} "))
4 Likes

Hi Alice,
The first one worked for me. Amazing and exciting!
Many thanks!

1 Like

Be careful about XSS. Such use of format! will interpret all values as HTML, which are allowed to include scripts and other markup dangerous for security and privacy. Even though there's no risk in the specific case of an integer, it becomes dangerous if you use any string types. I recommend using templates that apply HTML escaping automatically, because remembering to do it by hand every time it's needed is not reliable long term.

5 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.