7 个版本 (4 个破坏性更新)
| 0.5.0 | 2023 年 4 月 17 日 |
|---|---|
| 0.4.0 | 2023 年 3 月 1 日 |
| 0.3.0 | 2023 年 3 月 1 日 |
| 0.2.0 | 2023 年 2 月 28 日 |
| 0.1.2 | 2023 年 2 月 27 日 |
在 模板引擎 中排名第 82
每月下载量 336,238
在 207 个 Crates 中使用 (通过 attribute-derive-macro)
255KB
3.5K SLoC
interpolator
运行时 format! 的实现。
format
format! 的运行时版本。
接受一个字符串和一个上下文,其中包含 Formattable 值,返回一个字符串。
use std::collections::HashMap;
use template::{format, Formattable};
let formatted = format(
"{value:+05}", // could be dynamic
&[("value", Formattable::display(&12))].into_iter().collect::<HashMap<_,_>>(),
)
.unwrap();
assert_eq!(formatted, format!("{:+05}", 12));
write
write! 的运行时版本。
接受一个可变 Write,例如 &mut String,一个格式字符串和一个上下文,其中包含 Formattable 值。
use std::collections::HashMap;
use template::{write, Formattable};
let mut buf = String::new();
write(
&mut buf,
"{value:+05}", // could be dynamic
&[("value", Formattable::display(&12))].into_iter().collect::<HashMap<_,_>>(),
)
.unwrap();
assert_eq!(buf, format!("{:+05}", 12));
i 迭代格式
功能 iter 启用额外的格式 trait i,它允许使用格式字符串和可选的连接表达式格式化值列表。
语法是 {list:i(格式字符串, '{}' 是数组元素)(连接)},空连接也可以省略 {list:i({})}。如果省略连接,格式字符串 {} 也可以省略 {list:i}。
如果您需要在格式字符串或连接操作中使用 ),您可以在其中添加类似于 Rust 的 原始字符串 的 #(例如,#(({}))#)。
您还可以在格式字符串之前指定一个子切片的范围进行迭代,例如 {list:i1..4}。对于开放范围,范围界限也可以省略。要从末尾开始索引,可以使用负的范围界限。
您还可以通过只指定一个 isize 来索引单个值 {list:i1}。
使用 Formattable::iter 创建实现 iter 的 Formattable。
// HashMap macro
use collection_literals::hash;
use interpolator::{format, Formattable};
// Needs to be a slice of references because `Formattable::display` expects a
// reference
let items = [&"hello", &"hi", &"hey"].map(Formattable::display);
let items = Formattable::iter(&items);
let format_str = "Greetings: {items:i..-1(`{it}`)(, )} and {items:i-1..(`{it}`)}";
assert_eq!(
format(format_str, &hash!("items" => items))?,
"Greetings: `hello`, `hi` and `hey`"
);
# return Ok::<(), interpolator::Error>(())
特性
默认情况下,仅支持 Display,其余的 格式化特性 可以通过以下特性启用。
debug启用?、x?和X?特性指定符number启用x、X、b、o、e和E特性指定符pointer启用p特性指定符iter启用i特性指定符