From bdf42a33504d6cc78e7696cd9e89ea7c1e215858 Mon Sep 17 00:00:00 2001 From: Fabian Freyer Date: Mon, 15 May 2023 13:42:30 +0200 Subject: [PATCH] Add ContextProvider example --- examples/dynamic/main.rs | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 examples/dynamic/main.rs diff --git a/examples/dynamic/main.rs b/examples/dynamic/main.rs new file mode 100644 index 00000000..4adec2a2 --- /dev/null +++ b/examples/dynamic/main.rs @@ -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>( + &mut self, + key: S, + val: &T, + ) -> tera::Result<()> { + self.upper_layer.try_insert(key, val) + } + + fn find_value(&self, key: &str) -> Option> { + 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}"); +}