使用 Actix-Web 和 Handlebars 創建動態網頁
這是一個非常簡單的演示,關於在 Rust 中如何使用 Actix Web 和 Handlebars 來渲染 JSON 數據的網頁。本文將使你瞭解如何使用 Actix Web 創建簡單的 HTTP 服務器,以及如何處理 HTTP 請求。我們還將熟悉 Handlebars 以及如何使用 Handlebars 在模板中編譯和呈現 JSON 數據。
首先,我們創建一個 Rust 項目:
cargo new actix-web-blog
現在我們需要添加 actix-web 作爲項目的依賴項:
[dependencies]
actix-web = "4"
我們還需要添加更多的依賴項,以便能夠序列化 JSON 數據,並在運行時藉助 Handlebars 將 JSON 數據呈現到 web 頁面:
[dependencies]
actix-web = "4"
actix-files = "0.6.2"
serde_json = "1.0.83"
handlebars = { version = "4.3.3", features = ["dir_source"] }
-
actix-files:用於提供靜態文件
-
serde_json:序列化 / 反序列化 JSON 數據
-
handlebars:JSON 數據的模板引擎
編輯 main.rs 文件,寫入如下代碼:
1use actix_web::{web,HttpServer,HttpResponse,App};
2use actix_files::{Files};
3use serde_json::json;
4use handlebars::Handlebars;
5
6async fn home(hb: web::Data<Handlebars<'_>>) -> HttpResponse {
7 let posts = json!({
8
9 "posts":[
10 {
11 "title":"How to generate free energy using Wind",
12 "author":"Ramesh Vyas",
13 "image_path":"/static/images/wind.jpg"
14 },
15 {
16 "title":"Why Bees are important for human beings",
17 "author":"Nirvana",
18 "image_path": "/static/images/bee.jpg"
19 },
20 {
21 "title":"Try vegan for your rest life!",
22 "author":"Shiva",
23 "image_path":"/static/images/calf.jpg"
24 },
25
26 ]
27 });
28 let body = hb.render("posts", &posts).unwrap();
29 HttpResponse::Ok().body(body)
30}
31
32#[actix_web::main]
33async fn main() -> std::io::Result<()> {
34 let mut hbars = Handlebars::new();
35 hbars
36 .register_templates_directory(".html", "./static/")
37 .unwrap();
38 let hbars_ref = web::Data::new(hbars);
39
40 HttpServer::new( move || {
41 App::new()
42 .app_data(hbars_ref.clone())
43 .service(Files::new("/static", "static").show_files_listing())
44 .route("/", web::get().to(home))
45 })
46 .bind("127.0.0.1:8080")?
47 .run()
48 .await
49}
爲了簡單起見,本文采用了靜態 JSON 數據,這些數據也可以從任何外部源 (數據庫、文件……) 中填充。
我們使用 Handlebars 解析了 JSON 數據,並使用解析後的數據創建了頁面的 body。當訪問 / 時,頁面 body 被髮送到客戶端。
此外,我們還註冊了靜態文件目錄 static,以便 Handlebars 可以找到所需的模板 (posts.html)。使用這個模板,我們創建了一個響應頁面:
1<!DOCTYPE html>
2<html>
3 <head>
4 <meta charset="UTF-8" />
5 <title>My Personal Blog</title>
6 <link rel="stylesheet" href="static/css/style.css" type="text/css">
7 </head>
8 <body>
9 <h1>My Personal Blog</h1>
10 <section class="posts">
11 {{#each posts}}
12 <article class="post">
13 <img src="{{this.image_path}}" />
14 <h3>{{this.title}}</h3>
15 <h4>By: {{this.author}}</h4>
16 </article>
17 {{/each}}
18 </section>
19 </body>
20</html>
最後顯示如下圖所示:
完整代碼:https://github.com/rameshovyas/actix-web-blog/tree/master
本文翻譯自:
https://medium.com/@rameshovyas/how-to-create-dynamic-web-page-that-displays-json-data-in-rust-using-actix-web-and-handlebars-7e89e041fc8a
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/h4vVjFsQ0BQBl_-y27KtoA