Keats / tera2

28 stars 3 forks source link

Add global contexts #22

Closed Keats closed 6 months ago

Keats commented 7 months ago

This would be something that gets added to the context of each template automatically. For example it could be a SSG passing a timestamp/git sha automatically for every render

GandelXIV commented 6 months ago

I am working on a POC for this, and currently it works something like this:

let mut tera = Tera::new();
tera.global_context().insert("name", "John Doe");
let r = tera
    .render_str("Hello, {{ name }}!", &Context::new())
    .unwrap();
assert_eq!(r, "Hello, John Doe!".to_string());

Thoughts on ergonomics?

Keats commented 6 months ago

I was thinking of something like tera.insert_into_global_context(key, value). A bit more of a mouthful but hey. We can easily change it anyway before the release

GandelXIV commented 6 months ago

I was thinking of something like tera.insert_into_global_context(key, value). A bit more of a mouthful but hey. We can easily change it anyway before the release

This would be a simpler to get working, but what if the user wants to (for example) modify/remove keys, then we would just be re-implementing Context functions. So global_context() returning &mut Context and letting the user access it directly seemed like the best way.

GandelXIV commented 6 months ago

This has been completed in #25