index : livejrnl-rs.git

ascending towards madness

author berrysweet <berrysweet@noreply.codeberg.org> 2023-07-07 20:27:40.0 +00:00:00
committer berrysweet <berrysweet@noreply.codeberg.org> 2023-07-07 20:27:40.0 +00:00:00
commit
1927c8749635120d752b1a118d59dd0bbe43fa3e [patch]
tree
e0c086786eec23910652cdb0215c9530a632d56e
parent
69ace663ff1d3c26d45d03ff4bb36c37161f429e
download
1927c8749635120d752b1a118d59dd0bbe43fa3e.tar.gz

feat(functions): add include file function



Diff

 src/main.rs            |  1 +
 src/util/functions.rs  | 17 +++++++++++++++++
 src/util/templating.rs |  2 ++
 3 files changed, 20 insertions(+)

diff --git a/src/main.rs b/src/main.rs
index a80aaa8..277b089 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,6 +10,7 @@ mod data {
mod util {
	pub mod templating;
	pub mod filters;
	pub mod functions;
	pub mod journal;
}

diff --git a/src/util/functions.rs b/src/util/functions.rs
new file mode 100644
index 0000000..7a93723
--- /dev/null
+++ b/src/util/functions.rs
@@ -0,0 +1,17 @@
use minijinja::{Error, ErrorKind};

// https://docs.rs/minijinja/latest/minijinja/functions/index.html
fn include_file(template_dir: String, name: String) -> Result<String, Error> {
	let file_path = std::path::PathBuf::from(&template_dir);
	let file_path = file_path.join(name);

    std::fs::read_to_string(&file_path)
        .map_err(|e| Error::new(
            ErrorKind::InvalidOperation,
            "cannot load file"
        ).with_source(e))
}

pub fn register_functions(env: &mut minijinja::Environment<'_>) {
	env.add_function("include_file", include_file)
}
\ No newline at end of file
diff --git a/src/util/templating.rs b/src/util/templating.rs
index d17185e..18c1a99 100644
--- a/src/util/templating.rs
+++ b/src/util/templating.rs
@@ -9,6 +9,7 @@ use crate::data::formats;
use crate::util::journal;

use super::filters;
use super::functions;

pub fn get_templates(template: String) -> HashMap<String, String> {
	let template_path: PathBuf = PathBuf::from_str(&template).unwrap();
@@ -34,6 +35,7 @@ pub fn render_html(config: formats::RenderConfig, journal: journal::Journal, tem
	}

	filters::register_filters(env);
	functions::register_functions(env);

	let tmpl: minijinja::Template<'_, '_> = env.get_template(&config.template_index).unwrap();
	tmpl.render(context!(config => config, journal => journal)).unwrap_or_default()