teascade-generator/src/renderer.rs

60 lines
1.9 KiB
Rust

use std::fs::File;
use std::io::Read;
use pulldown_cmark::{html, Parser};
use config::{Config, SinglePageConfigs};
use template::Template;
pub fn render_markdown_content(config: &SinglePageConfigs) -> Result<String, String> {
if let Some(parent) = config.page_config_path.parent() {
let path = parent.with_file_name(&config.page_config.page.content_path);
match File::open(&path) {
Ok(mut file) => {
let mut content = String::new();
file.read_to_string(&mut content).ok();
let parser = Parser::new(&content);
let mut markdown = String::new();
html::push_html(&mut markdown, parser);
Ok(markdown)
}
Err(_) => Err(format!("Failed to open file: {}", path.to_str().unwrap())),
}
} else {
Err(format!(
"Failed to get page config parent: {}",
config.page_config_path.to_str().unwrap()
))
}
}
pub fn render_navbar(
config: &Config,
item_template: Template,
image_item_template: Template,
) -> Result<String, String> {
let mut navbar_str = String::new();
if let Some(navbar) = config.global_config.navbar.clone() {
for item_str in navbar.items {
if let Some(item) = navbar.item_map.get(&item_str) {
let data = Template::navbar_item_data_from(item.clone());
if item.image_url.is_some() {
navbar_str += &*image_item_template.render(&data);
} else {
navbar_str += &*item_template.render(&data);
}
} else {
return Err(format!(
"Navbar item does not exist: navbar.item.{}",
item_str
));
}
}
Ok(navbar_str)
} else {
Err("Attempted to render navbar without navbar".to_owned())
}
}