summaryrefslogtreecommitdiff
path: root/src/template.rs
diff options
context:
space:
mode:
authorDaniel Silverstone <dsilvers+gitlab@digital-scurf.org>2021-04-08 09:03:50 +0000
committerDaniel Silverstone <dsilvers+gitlab@digital-scurf.org>2021-04-08 09:03:50 +0000
commit924fc1add2de3edac4ad4b1097a3bbbb73d0ad50 (patch)
treee5c9689e1ff60953502faf55eacb8a82c2726b8a /src/template.rs
parent518e7dc2d5f97387702af0a300cc2842bd0deec6 (diff)
parent0b0cc421e79bff9f8692e8c771c5e72ee4414032 (diff)
downloadjt2-924fc1add2de3edac4ad4b1097a3bbbb73d0ad50.tar.gz
Merge branch 'tera' into 'main'
feat! add support for tera templates for new journal entries Closes #8 and #10 See merge request larswirzenius/jt!11
Diffstat (limited to 'src/template.rs')
-rw-r--r--src/template.rs46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/template.rs b/src/template.rs
new file mode 100644
index 0000000..89c1a15
--- /dev/null
+++ b/src/template.rs
@@ -0,0 +1,46 @@
+use crate::error::JournalError;
+use std::path::Path;
+use tera::{Context, Tera};
+
+const NEW_ENTRY: &str = r#"[[!meta title="{{ title }}"]]
+[[!meta date="{{ date }}"]]
+
+This is the default template.
+"#;
+
+pub struct Templates {
+ tera: Tera,
+}
+
+impl Templates {
+ pub fn new(dirname: &Path) -> Result<Self, JournalError> {
+ let glob = format!("{}/.config/templates/*", dirname.display());
+ let mut tera = Tera::new(&glob).expect("Tera::new");
+ add_default_template(&mut tera, "new_entry", NEW_ENTRY);
+ Ok(Self { tera })
+ }
+
+ pub fn new_draft(&self, context: &Context) -> Result<String, JournalError> {
+ self.render("new_entry", &context)
+ }
+
+ fn render(&self, name: &str, context: &Context) -> Result<String, JournalError> {
+ match self.tera.render(name, &context) {
+ Ok(s) => Ok(s),
+ Err(e) => match e.kind {
+ tera::ErrorKind::TemplateNotFound(x) => Err(JournalError::TemplateNotFound(x)),
+ _ => Err(JournalError::TemplateRender(name.to_string(), e)),
+ },
+ }
+ }
+}
+
+fn add_default_template(tera: &mut Tera, name: &str, template: &str) {
+ let context = Context::new();
+ if let Err(err) = tera.render(name, &context) {
+ if let tera::ErrorKind::TemplateNotFound(_) = err.kind {
+ tera.add_raw_template(name, template)
+ .expect("Tera::add_raw_template");
+ }
+ }
+}