-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
main.rs
69 lines (59 loc) · 1.83 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#![allow(clippy::let_unit_value)]
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use minijinja::value::{from_args, Object, Value};
use minijinja::{Environment, Error, State};
#[derive(Debug)]
struct Cycler {
values: Vec<Value>,
idx: AtomicUsize,
}
impl fmt::Display for Cycler {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "cycler")
}
}
impl Object for Cycler {
fn call(&self, _state: &State, args: &[Value]) -> Result<Value, Error> {
// we don't want any args
from_args(args)?;
let idx = self.idx.fetch_add(1, Ordering::Relaxed);
Ok(self.values[idx % self.values.len()].clone())
}
}
fn make_cycler(_state: &State, args: Vec<Value>) -> Result<Value, Error> {
Ok(Value::from_object(Cycler {
values: args,
idx: AtomicUsize::new(0),
}))
}
#[derive(Debug)]
struct Magic;
impl fmt::Display for Magic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "magic")
}
}
impl Object for Magic {
fn call_method(&self, _state: &State, name: &str, args: &[Value]) -> Result<Value, Error> {
if name == "make_class" {
// single string argument
let (tag,): (&str,) = from_args(args)?;
Ok(Value::from(format!("magic-{}", tag)))
} else {
Err(Error::new(
minijinja::ErrorKind::ImpossibleOperation,
format!("object has no method named {}", name),
))
}
}
}
fn main() {
let mut env = Environment::new();
env.add_function("cycler", make_cycler);
env.add_global("magic", Value::from_object(Magic));
env.add_template("template.html", include_str!("template.html"))
.unwrap();
let tmpl = env.get_template("template.html").unwrap();
println!("{}", tmpl.render(&()).unwrap());
}