Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Askama

Askama 基于 Jinja 实现的模板渲染引擎。 它会在编译时根据用户定义的用于保存模板上下文的 struct,从你的模板中生成 Rust 代码。 具体示例如下:

欢迎所有反馈!如有 bug、文档需求或其他任何意见,请随时提交到askama github仓库issues.

如果你想在线体验 Askama 的代码生成,可以访问 Askama Playground

特性亮点

  • 使用熟悉且易用的语法构建模板
  • 受益于 Rust 类型系统带来的安全性
  • 模板代码会被编译到你的 crate 中,以获得最佳性能
  • 提供调试功能,协助你进行模板开发
  • 模板必须是有效的 UTF-8,并渲染生成 UTF-8 输出
  • 可在稳定版 Rust 上运行

模板中支持的功能

  • 模板继承
  • 循环、if/else 语句和 include 支持
  • 宏支持
  • 变量(不可变变量)
  • 多种内置过滤器,并支持使用自定义过滤器
  • 使用 - 标记抑制空白字符
  • 可选择关闭 HTML 转义
  • 语法自定义

快速开始

首先,在你的 crate 的 Cargo.toml 中添加以下内容:

# in [dependencies] section 版本号根据需要更新
askama = "0.14.0"

然后,在 crate 根目录下创建一个名为 templates 的目录。在其中创建一个名为 hello.html 的文件,内容如下:

Hello, {{ name }}!

在你的 crate 内的任意 Rust 文件中,添加以下代码:

use askama::Template; // bring trait in scope

#[derive(Template)] // this will generate the code...
#[template(path = "hello.html")] // using the template in this path, relative
                                 // to the `templates` dir in the crate root
struct HelloTemplate<'a> { // the name of the struct can be anything
    name: &'a str, // the field name should match the variable name
                   // in your template
}

fn main() {
    let hello = HelloTemplate { name: "world" }; // instantiate your struct
    println!("{}", hello.render().unwrap()); // then render it.
}

现在你应该能够编译并运行这段代码了,正确运行输出结果应为:

Hello, world!