Home > database >  How do I display html files with rocket.rs
How do I display html files with rocket.rs

Time:06-30

I am new to rust and I am trying to build a simple webpage with HTML.

This is my code:

use rocket::*;
use rocket::response::content::Html;

#[get("/")]
fn index() -> content::Html<&'static str> {
    content::Html(r#"
        <title>GCD Calculator</title>
        <form action="/gcd" method="post">
            <input type="text" name="n" />
            <input type="text" name="n" />
            <button type="submit">Compute GCD</button>
        </form>
    "#)
}

#[launch]
fn rocket()->_{
    rocket::build().mount("/", routes![index])
}

But it returns the error:

   Compiling hello-rocket v0.1.0 (/home/garuda/dev/Rust/Rocket/hello-rocket)
error[E0432]: unresolved import `rocket::response::content::Html`
 --> src/main.rs:2:5
  |
2 | use rocket::response::content::Html;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `Html` in `response::content`

error[E0433]: failed to resolve: use of undeclared crate or module `content`
 --> src/main.rs:5:15
  |
5 | fn index() -> content::Html<&'static str> {
  |               ^^^^^^^ use of undeclared crate or module `content`

error[E0433]: failed to resolve: use of undeclared crate or module `content`
 --> src/main.rs:6:5
  |
6 |     content::Html(r#"
  |     ^^^^^^^ use of undeclared crate or module `content`

Some errors have detailed explanations: E0432, E0433.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `hello-rocket` due to 3 previous errors

I know for sure that this module exists because https://api.rocket.rs/v0.4/rocket/response/content/struct.Html.html

CodePudding user response:

In the (preview) Rocket 0.5.0-rc.2, the struct Html was renamed to RawHtml. Replace Html with RawHtml and it'll work.

See also the changelog:

  • Content-Type content responder type names are now prefixed with Raw.

CodePudding user response:

You can either use the full path name to refer to that module, ie.

#[get("/")]
fn index() -> rocket::response::content::Html<&'static str> {
  rocket::response::content::Html(...)
}

Or add that specific module to the current namespace, with

use rocket::response::content;

In your code, you were only adding everything in the rocket module in your namespace with use rocket::*, and the Html struct with use::rocket::response::content::Html, so as is you could also use Html directly:

fn index() -> Html<&'static str> {
  Html(...)
}
  • Related