#编译时 #宏推导 #运行时 #静态检查

无std boilerplate

最小的编译时Rust模板引擎

12个版本 (2个稳定版)

1.0.1 2024年8月17日
1.0.0 2023年7月5日
0.2.5 2023年1月2日
0.2.4 2022年12月28日
0.0.0 2017年2月13日

模板引擎 中排名 86

Download history 582/week @ 2024-05-01 406/week @ 2024-05-08 265/week @ 2024-05-15 335/week @ 2024-05-22 298/week @ 2024-05-29 315/week @ 2024-06-05 350/week @ 2024-06-12 339/week @ 2024-06-19 364/week @ 2024-06-26 447/week @ 2024-07-03 433/week @ 2024-07-10 400/week @ 2024-07-17 317/week @ 2024-07-24 305/week @ 2024-07-31 342/week @ 2024-08-07 460/week @ 2024-08-14

每月下载量 1,464
9 个crate中使用(直接使用8个)

CC0许可

31KB
431

boilerplate


boilerplate 是一个没有运行时依赖的静态检查Rust模板引擎。可以使用两种方式使用 boilerplate::boilerplate,一个函数式宏,以及 boilerplate::Boilerplate,一个推导宏。

函数式宏

use boilerplate::boilerplate;

let foo = true;
let bar: Result<&str, &str> = Ok("yassss");

let output = boilerplate!(
"%% if foo {
Foo was true!
%% }
%% match bar {
%%   Ok(ok) => {
Pretty good: {{ ok }}
%%   }
%%   Err(err) => {
Not so great: {{ err }}
%%   }
%% }
");

assert_eq!(output, "Foo was true!\nPretty good: yassss\n");

推导宏

在您想要用作模板上下文的类型上推导 Boilerplate

use boilerplate::Boilerplate;

#[derive(Boilerplate)]
struct MyTemplateTxt {
  foo: bool,
  bar: Result<String, Box<dyn std::error::Error>>,
}

boilerplate 模板代码和插值都是Rust,因此错误在编译时进行检查,模板语言易于学习

%% if self.foo {
Foo was true!
%% }
%% match &self.bar {
%%   Ok(ok) => {
Pretty good: {{ ok }}
%%   }
%%   Err(err) => {
Not so great: {{ err }}
%%   }
%% }

Boilerplate 宏提供 Display 实现,因此您可以实例化模板上下文并将其转换为字符串

let rendered = MyTemplateTxt { foo: true, bar: Ok("hello".into()) }.to_string();

或者在使用格式字符串时使用它

println!("The output is: {}", MyTemplateTxt { foo: false, bar: Err("hello".into()) });

boilerplate 的实现非常简单。尝试使用 cargo-expand 展开宏 Boilerplate 并检查推导的 Display 实现,以及调试模板问题。

快速入门

boilerplate 添加到项目的 Cargo.toml

[dependencies]
boilerplate = "*"

templates/my-template.txt 中创建模板

Foo is {{self.n}}!

定义、实例化和渲染模板上下文

use boilerplate::Boilerplate;

#[derive(Boilerplate)]
struct MyTemplateTxt {
  n: u32,
}

assert_eq!(MyTemplateTxt  { n: 10 }.to_string(), "Foo is 10!\n");

示例

有关更多信息示例,请参阅 文档

依赖

~0.8–1.3MB
~29K SLoC