DEV Community

Cover image for Creating a Web Page with Actix-Web (Rust )
Michael Olayemi
Michael Olayemi

Posted on

Creating a Web Page with Actix-Web (Rust )

Overview
In this tutorial, we are going to build a simple website using actix, a stable framework based on rust programming language.
The simple website is called bookstore: it is a simple website for book index.

Rust is a young language, coming from Java background was so awesome, when I pick up rust, I fell in love with the language and felt like building everything in rust.

There are cool frameworks in rust to build a website but I choose actix because to me it doesn't have any con yet.

Let dive in, create an empty project with cargo (cargo new bookstore). Open the cargo.toml and add the following dependencies :
actix-web="3"
actix-files="0.4.0"
serde_json = "1.0.53"
handlebars = { version = "4.1.4", features = ["dir_source"] }

The actix-web will help us to access the actix web framework.
actix-files will help us to add static files to our project.
Handlebar is a template engine that will help us to create template for our web page.

Using Handlebars
In the main.rs, paste the code below

use actix_files::{Files, NamedFile};
use actix_web::{web, App, HttpResponse, HttpServer, Result};
use handlebars::Handlebars;
use serde_json::json;

async fn index(hb: web::Data<Handlebars<'_>>) -> HttpResponse {
    let data = json!({
        "project_name": "Book Store",
        "books":[
            {
                "name":"Harry Potter",
                "author":"J K Rowlings",
                "image_path":"/static/image/download.jpeg"
            },
            {
                "name":"Lord of the ring",
                "author":"Tolken",
                "image_path": "/static/image/lord_of.jpeg"
            },
            {
                "name":"Americanah",
                "author":"Chimamada Adichie",
                "image_path":"/static/image/americanah.jpeg"
            },
            {
                "name":"Elon Musk",
                "author":"#####",
                "image_path":"/static/image/elon.jpeg"
            },
        ]


    });

    let body = hb.render("index", &data).unwrap();
    HttpResponse::Ok().body(body)


}
Enter fullscreen mode Exit fullscreen mode

Handlebar helps load and compile the json before before using them. The data created with json will be used in our project.

In the main function, we have to initialize the handlebar and register the templates_directory.

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let mut handlebars = Handlebars::new();
    handlebars
        .register_templates_directory(".html", "./static/")
        .unwrap();
    let handlebars_ref = web::Data::new(handlebars);

    println!("listening on port 8080");
    HttpServer::new(move || {
        App::new()
            .app_data(handlebars_ref.clone())
            .service(Files::new("/static", "static").show_files_listing())
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:9090")?
    .run()
    .await
}
Enter fullscreen mode Exit fullscreen mode

Create a directory in the root folder called static and inside the static create two folders for images and css file. Inside the directory create index.html and paste the code below:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>{{project_name}}</title>
    <link rel="stylesheet" href="static/css/index.css" type="text/css">
  </head>
  <body>
    <h1>{{project_name}}</h1>
    <section class="books">
      {{#each books}}
        <article class="book">
          <h3>{{this.name}}</h3>
          <img src="{{this.image_path}}" />
            <h4>Author: {{this.author}}</h4>
        </article>
      {{/each}}
    </section>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Handlebar help us to render the data created in json into the html template, {{project_name}} will be the project name. {{#each books}} helps loop through the json to create the book index without writing a separate tag for each index.

When you are done, run cargo run in your terminal and access the page with 127.0.0.1:9090

bookindex

Head over to github to download the full code.

If you find this article useful and will like to tip me with $1 worth of cryptocurrency, you can do it here and I will really appreciate.

Thanks

Discussion (0)