Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8287

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T11:43:07+00:00 2024-11-28T11:43:07+00:00

πŸš€ Day 36: Rocketing Ahead with Templating – Crafting Dynamic Web Content in Rust!

  • 60k

Hello, space cadets of the web development galaxy! On the 36th day of our interstellar journey through the Rocket framework, I stumbled upon the star-studded craft of templating. Now, sit back, relax, and watch as we spin the yarn of dynamic web page creation with Rocket. 🌐🎨


🌟 The Basics of Templating: Weaving the Web Page Tapestry 🌟

First things first! Templating is like being a web wizard, conjuring dynamic content into your static HTML pages. It's the ancient art of inserting data variables into placeholders, allowing for a single HTML file to display different content based on different context – truly a magical experience! πŸ§™β€β™‚οΈβœ¨


πŸš€πŸ“œ Rocket Templating: The Spellbook of Dynamic Web Development πŸ“œπŸš€

Rocket, being the sophisticated framework it is, comes equipped with a templating engine that transforms your Rust structs into HTML fairy dust.

We can use tera crate for this purpose. For example, we can create a templates directory in our project and put our HTML files in it. Then we can use tera to render these HTML files. But the html files should haveΒ .tera extension. For example, if we have index.html file, we should rename it to index.html.tera. Then we can use tera to render this file.

Here's the breakdown of the incantation, I mean code, we've crafted today:

🧬 The Data Structure: User 🧬

#[derive(Serialize)] struct User {     first_name: String,     last_name: String, } 
Enter fullscreen mode Exit fullscreen mode

Here we define a User struct. Think of it as a blueprint for the data our web page will showcase. #[derive(Serialize)] is like whispering to Rust: “Hey, make sure you can turn this into a JSON-like format when needed.”

🎩 The JSON Spell: hello Route 🎩

#[get("/hello")] fn hello() -> RawJson<&'static str> {     RawJson(         r#"         {             "status": "Success",             "message": "Hello, API",         }     "#,     ) } 
Enter fullscreen mode Exit fullscreen mode

The hello function is where we cast a simple spell to return a JSON response. RawJson wraps our static string in a mystical JSON robe, ready to be conjured upon an API call. It's like sending a telepathic message in a bottle into the void of the internet.

πŸ“œ The 404 Scroll: not_found Catcher πŸ“œ

#[catch(404)] fn not_found(req: &Request) -> String {     format!(         "Oh noπŸ₯²! We couldn't find the requested path '{}'",         req.uri()     ) } 
Enter fullscreen mode Exit fullscreen mode

This scroll, err, function, comes into play when someone ventures into uncharted territories of our application. Instead of leaving them in the dark abyss, we gently nudge them back with a personalized message. “Not all who wander are lost, but you, my friend, definitely are.”

🎨 The Masterpiece: home_page Route 🎨

#[get("/")] fn home_page() -> Template {     let context = User {         first_name: "Aniket".to_string(),         last_name: "Botre".to_string(),     };     Template::render("index", &context) } 
Enter fullscreen mode Exit fullscreen mode

The home_page function is where our tapestry of HTML and data comes to life. We create an instance of User and pass it to our template called index. It's like telling a story where the characters come alive with each visitor.

πŸš€ The Launchpad: rocket Function πŸš€

#[launch] fn rocket() -> _ {     rocket::build()         .mount("/", routes![home_page, hello])         .register("/", catchers![not_found])         .attach(Template::fairing()) } 
Enter fullscreen mode Exit fullscreen mode

This is where we assemble our spaceship. We mount our routes and catchers and attach the template fairing, which is Rocket's way of saying “Prepare the templating engines for lift-off!”. πŸš€

πŸ–ΌοΈ The Canvas: templates/index.html.tera πŸ–ΌοΈ

<html lang="en">  <head>   <title>Rocket framework</title>   <style>     body {       margin: 0;       padding: 0;       font-family: Arial, sans-serif;       background-color: #073B3A;     }      main {       display: flex;       justify-content:         center;       align-items: center;       height: 100vh;     }      section {       display: flex;       justify-content: space-between;       align-items: center;       width: 80%;     }      .left-side {       width: 50%;     }      .right-side {       width: 50%;       height: 50%;     }      img {       width: 100%;       height: 100%;       border: 2px solid #DDB771;     }      .title {       font-size: 2.5rem;       color: #DDB771;     }      .sub-title {       font-size: 1.5rem;       color: #8ada79;     }   </style> </head>  <body>   <main>     <section>       <div class="left-side">         <h1 class="title">           This web app is built using RocketπŸš€ framework which uses RustπŸ¦€         </h1>         <p class="sub-title">           Welcome,           {{first_name}}           {{last_name}}! You are viewing a web app which is built using RustπŸ¦€         </p>       </div>       <div class="right-side">         <img src="https://i.redd.it/9t12lnng69i41.png" alt="Rust logo" />       </div>     </section>   </main> </body>  </html> 
Enter fullscreen mode Exit fullscreen mode

Our HTML file is the canvas where our data will paint its story. The .tera extension indicates that we're using Tera templates, a templating language for Rust. It's like HTML, but with superpowers. The {{first_name}} and {{last_name}} placeholders are where our User data will display its colors.


🌌 The Final Frontier: The Web Page Output 🌌

After running our Rocket application, I was graced with a webpage that displays my name in a personal welcome message. It's like watching your child take their first steps into the digital world. Tears of joy.πŸ₯²

Code output


My final src/main.rs file looks like this:

#[macro_use] extern crate rocket;  use rocket::response::content::RawJson; use rocket::Request; use rocket_dyn_templates::Template; use serde::Serialize;  #[derive(Serialize)] struct User {     first_name: String,     last_name: String, }  #[get("/hello")] fn hello() -> RawJson<&'static str> {     RawJson(         r#"         {             "status": "Sucess",             "message": "Hello, API",         }     "#,     ) }  #[catch(404)] fn not_found(req: &Request) -> String {     format!(         "Oh noπŸ₯²! We couldn't find the requested path '{}'",         req.uri()     ) }  #[get("/")] fn home_page() -> Template {     let context = User {         first_name: "Aniket".to_string(),         last_name: "Botre".to_string(),     };     Template::render("index", &context) }  #[launch] fn rocket() -> _ {     rocket::build()         .mount("/", routes![home_page, hello])         .register("/", catchers![not_found])         .attach(Template::fairing()) } 
Enter fullscreen mode Exit fullscreen mode


πŸŽ‡ Conclusion: The Enchantment of Rocket Templating πŸŽ‡

And there we have it, space cadets! We've navigated through the asteroid field of Rocket templating and emerged victorious. With Rocket as our trusty sidekick, the cosmos of web development is ours for the taking. May your templates always compile, and your web pages forever sparkle in the vastness of cyberspace! πŸš€βœ¨

Until next time, keep your code editor close and your browser closer. Happy templating! πŸŽ¨πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

100daysofcodeprogrammingrustwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.