1 个不稳定版本
0.2.0 | 2023年5月22日 |
---|
#321 在 模板引擎
48KB
1K SLoC
Handybars
简介
这是一个用于模板扩展的小型库。语法基于 handlebars,但它 仅 支持变量的扩展。没有 #if
或 #each
,只有 {{ variable }}
。如果您需要实际的 handlebars 支持,请考虑 handlebars crate。
它没有依赖项,并且设计有非常简单的 API。
用法
use handybars::{Context, Variable};
let ctx = Context::new().with_define("hello".parse().unwrap(), "world");
assert_eq!(ctx.render("hello {{ hello }}"), Ok("hello world".to_owned()));
您还可以定义对象
# use handybars::{Context, Variable, Object};
# let mut ctx = Context::new().with_define("hello".parse().unwrap(), "world");
ctx.define("obj".parse().unwrap(), Object::new().with_property("a", "value"));
assert_eq!(ctx.render("object a: {{ obj.a }}"), Ok("object a: value".to_owned()));
您甚至可以有嵌套对象
# use handybars::{Context, Variable, Object};
# let mut ctx = Context::new().with_define("hello".parse().unwrap(), "world");
ctx.define("obj".parse().unwrap(), Object::new().with_property("b", Object::new().with_property("c", "value")));
assert_eq!(ctx.render("nested: {{ obj.b.c }}"), Ok("nested: value".to_owned()));
注意,对象不能直接扩展
use handybars::{Context, Variable, Object, Error};
let ctx = Context::new().with_define("world".parse().unwrap(), Object::new().with_property("a", "p1"));
assert_eq!(ctx.render("{{world}}"), Err(Error::TriedToExpandObject(Variable::single("world"))));