-
Notifications
You must be signed in to change notification settings - Fork 290
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
249b45d
commit bdf42a3
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"); | ||
} |