【Rust】Rust template engine ~ Askama / 入門編 ~

◾️はじめに

今回は、Rustテンプレートエンジンの「Askama」について扱う

目次

【0】Rustテンプレートエンジン一覧
【1】Askama
 1)特徴:型安全
【2】インストール
【3】Hello world
 1)フォルダ構成
 2)コード
 3)補足:変数名をわざと間違えてみる

【0】Rustテンプレートエンジン一覧

[1] Askama << 今回のテーマ
[2] Tera
[3] Maud
[4] Handlebars-rust

Tera
https://keats.github.io/tera/
https://github.com/Keats/tera

【1】Askama

* Rust のテンプレート

https://github.com/askama-rs/askama
https://askama.readthedocs.io/en/stable/

1)特徴:型安全

* コンパイル時にチェックを行う
 => テンプレの変数名間違えた場合、コンパイルエラーで把握できる

【2】インストール

* Cargo.tomlに追加する
 => 「cargo add askama」でもいい

Cargo.toml

[dependencies]
askama = "0.14.0"

【3】Hello world

* 以下の公式の「How to get started」をやってみる

https://github.com/askama-rs/askama?tab=readme-ov-file#how-to-get-started

1)フォルダ構成

hello_world ... Rustプロジェクト(任意の名前でOK)
    ├─src
    │  └─ main.rs ... メイン関数
    ├─Cargo.toml ... 「【2】インストール」参照
    └─templates ... 自分で用意しておく
      └─ hello.html ... 自分で用意

2)コード

hello.html

Hello, {{ name }}!

main.rs

use askama::Template;

#[derive(Template)]
#[template(path = "hello.html")] // Templateを指定
struct HelloTemplate<'a> { 
    name: &'a str,
}

fn main() {
    let hello = HelloTemplate { name: "world" };
    println!("{}", hello.render().unwrap()); // Hello, world!
}

3)補足:変数名をわざと間違えてみる

fn main() {
    let hello = HelloTemplate { xxx: "world" }; // 変数名を間違える
    println!("{}", hello.render().unwrap());
}

ビルドエラー例

$ cargo build
... 略
error[E0560]: struct `HelloTemplate<'_>` has no field named `xxx`
  --> src/main.rs:11:33
   |
11 |     let hello = HelloTemplate { xxx: "world" };
   |                                 ^^^ `HelloTemplate<'_>` does not have this field
   |
   = note: available fields are: `name`

For more information about this error, try `rustc --explain E0560`.
error: could not compile `hello_world ` (bin "hello_world") due to 1 previous error

参考文献

https://zenn.dev/nodamushi/articles/a30e347eeb68db

関連記事

Rust ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/22/234808
Rust ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2025/11/26/224648
Rust ~ Axum / 入門編 ~
https://dk521123.hatenablog.com/entry/2023/09/02/224707
Rust ~ Axum / REST ~
https://dk521123.hatenablog.com/entry/2025/11/27/145159