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
每月下载量 1,464
在 9 个crate中使用(直接使用8个)
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