Skip to content

Commit

Permalink
Add ContextProvider example
Browse files Browse the repository at this point in the history
  • Loading branch information
fabianfreyer committed May 15, 2023
1 parent 249b45d commit bdf42a3
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions examples/dynamic/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use serde_json::Value;
use std::{borrow::Cow, env};
use tera::{Context, ContextProvider, Tera};

#[derive(Clone)]
struct MyContext {
upper_layer: Context, // for overrides
}

impl MyContext {
pub fn new() -> Self {
Self { upper_layer: Context::new() }
}
}

impl ContextProvider for MyContext {
fn try_insert<T: serde::Serialize + ?Sized, S: Into<String>>(
&mut self,
key: S,
val: &T,
) -> tera::Result<()> {
self.upper_layer.try_insert(key, val)
}

fn find_value(&self, key: &str) -> Option<Cow<Value>> {
if let Some(val) = self.upper_layer.find_value(key) {
return Some(val);
}

env::var(key.to_uppercase()).map(Value::String).map(Cow::Owned).ok()
}

fn into_json(self) -> Value {
let Value::Object(map) = self.upper_layer.into_json() else { unreachable!() };
Value::Object(map)
}
}

fn main() {
let ctx = MyContext::new();

let output = Tera::one_off("Hello {{ user }}!", &ctx, false).unwrap();

println!("{output}");
}

0 comments on commit bdf42a3

Please sign in to comment.