4 个版本 (2 个重大更改)

0.3.1 2024 年 8 月 20 日
0.3.0 2024 年 8 月 2 日
0.2.0 2024 年 7 月 16 日
0.0.1 2024 年 6 月 17 日

#14 in 模板引擎

Download history 121/week @ 2024-06-14 15/week @ 2024-06-21 172/week @ 2024-07-12 2678/week @ 2024-07-19 7150/week @ 2024-07-26 7474/week @ 2024-08-02 7449/week @ 2024-08-09 6153/week @ 2024-08-16

每月 29,302 次下载
6 个 Crates 中使用 (5 个直接使用)

MIT/Apache

105KB
2K SLoC

rinja

Crates.io GitHub Workflow Status Book docs.rs

Rinja 实现了一个基于 Jinja 的模板渲染引擎,并在编译时根据用户定义的 struct 生成类型安全的 Rust 代码来保存模板的上下文。以下是一个示例。它是 Askama 的一个分支。

欢迎所有反馈!请随时提交错误报告、文档请求和其他反馈到 问题跟踪器

您可以在我们的书中找到有关我们的语法、功能和配置的文档:rinja.readthedocs.io

如果您想在线尝试 rinja 的代码生成,请查看我们的 Rinja 操场

功能亮点

  • 使用熟悉且易于使用的语法构建模板
  • 享受 Rust 类型系统提供的安全性
  • 模板代码在编译时编译到您的 crate 中,以实现最佳性能
  • 可选的内置 Actix、Axum、Rocket 和 warp 网络框架支持
  • 调试功能,帮助您进行模板开发
  • 模板必须是有效的 UTF-8,并且渲染时必须产生 UTF-8
  • 在稳定 Rust 上运行

模板中支持的功能

  • 模板继承
  • 循环、if/else 语句和 include 支持
  • 宏支持
  • 变量(不允许可变性)
  • 一些内置过滤器,以及使用您自己的过滤器的能力
  • 使用 '-' 标记抑制空白
  • 可选的 HTML 转义
  • 语法自定义

如何开始

首先,将 rinja 依赖项添加到您的 crate 的 Cargo.toml

cargo add rinja

现在在您的 crate 根目录中创建一个名为 templates 的目录。在其中创建一个名为 hello.html 的文件,包含以下内容

Hello, {{ name }}!

在任何您的 crate 中的 Rust 文件中添加以下内容

use rinja::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.
}

现在您应该能够编译并运行此代码。

依赖项

~4–10MB
~97K SLoC