Actix-web と Tera を使って Web アプリケーションを作る第一歩です。
前回は、Axum と Askama を使いましたが、調べてみると Actix-web と Tera が主流らしいので、 こちらでステップバイステップでアプリケーションを作っていきたいと思います。
このサンプルは AI が作ったもので、2箇所の修正で動くようになりました。これをベースに Web アプリケーションを作っていきたいと思います。
[package]
name = "tera"
version = "0.1.0"
edition = "2024"
[dependencies]
actix-web = "4.11.0"
serde = "1.0.226"
tera = "1.18"
use actix_web::{web, App, HttpServer, Responder, HttpResponse};
use tera::Tera;
// Todoのデータ構造を定義(例:インメモリ)
#[derive(serde::Serialize, Debug)]
struct Todo {
id: usize,
title: String,
completed: bool,
}
// Todoリストのハンドラ
async fn list_todos(tera: web::Data<Tera>) -> impl Responder
{
let todos = vec![
Todo { id: 1, title: "Go to the store".to_string(), completed: false },
Todo { id: 2, title: "Buy milk".to_string(), completed: true },
];
let mut context = tera::Context::new();
context.insert("todos", &todos);
let rendered = tera.render("index.html", &context).unwrap(); // index.htmlをレンダリング
HttpResponse::Ok().body(rendered)
}
#[actix_web::main]
async fn main() -> std::io::Result<()>
{
HttpServer::new(|| {
let tera = Tera::new("templates/**/*").expect("Failed to initialize Tera"); // templatesディレクトリ内のHTMLを読み込む
App::new()
.app_data(web::Data::new(tera))
.route("/", web::get().to(list_todos))
// 他のルート(追加、完了、削除など)も追加
})
.bind("127.0.0.1:8080")?
.run()
.await
}
プロジェクトのルートディレクトリに templates というディレクトリを作り、 その中に次の index.html を作ります。
<!DOCTYPE html>
<html lang="ja">
<head>
<title>Todo</title>
</head>
<body>
<h1>Todo</h1>
<ul>
{% for todo in todos %}
<li>
<input type="checkbox" {% if todo.completed %}checked{% endif %}>
{{ todo.title }}{% else %}{{ todo.title }}
<!-- <del>{{ todo.title }}</del>{% else %}{{ todo.title }} -->
</li>
{% endfor %}
</ul>
</body>
</html>
ターミナルでプロジェクトのルートディレクトリに移動して、cargo run とコマンドしてサーバーを起動してください。 そしてお使いのブラウザで localhost:8080 もしくは 127.0.0.1:8080 を開いてください。