You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.5KB

  1. use std::collections::HashMap;
  2. use std::path::{PathBuf};
  3. use tera::{GlobalFn, Value, from_value, to_value, Result};
  4. use content::{Page, Section};
  5. use utils::site::resolve_internal_link;
  6. pub fn make_get_page(all_pages: &HashMap<PathBuf, Page>) -> GlobalFn {
  7. let mut pages = HashMap::new();
  8. for page in all_pages.values() {
  9. pages.insert(page.file.relative.clone(), page.clone());
  10. }
  11. Box::new(move |args| -> Result<Value> {
  12. match args.get("path") {
  13. Some(val) => match from_value::<String>(val.clone()) {
  14. Ok(v) => {
  15. match pages.get(&v) {
  16. Some(p) => Ok(to_value(p).unwrap()),
  17. None => Err(format!("Page `{}` not found.", v).into())
  18. }
  19. },
  20. Err(_) => Err(format!("`get_page` received path={:?} but it requires a string", val).into()),
  21. },
  22. None => Err("`get_page` requires a `path` argument.".into()),
  23. }
  24. })
  25. }
  26. pub fn make_get_section(all_sections: &HashMap<PathBuf, Section>) -> GlobalFn {
  27. let mut sections = HashMap::new();
  28. for section in all_sections.values() {
  29. sections.insert(section.file.relative.clone(), section.clone());
  30. }
  31. Box::new(move |args| -> Result<Value> {
  32. match args.get("path") {
  33. Some(val) => match from_value::<String>(val.clone()) {
  34. Ok(v) => {
  35. match sections.get(&v) {
  36. Some(p) => Ok(to_value(p).unwrap()),
  37. None => Err(format!("Section `{}` not found.", v).into())
  38. }
  39. },
  40. Err(_) => Err(format!("`get_section` received path={:?} but it requires a string", val).into()),
  41. },
  42. None => Err("`get_section` requires a `path` argument.".into()),
  43. }
  44. })
  45. }
  46. pub fn make_get_url(permalinks: HashMap<String, String>,) -> GlobalFn {
  47. Box::new(move |args| -> Result<Value> {
  48. match args.get("link") {
  49. Some(val) => match from_value::<String>(val.clone()) {
  50. Ok(v) => match resolve_internal_link(&v, &permalinks) {
  51. Ok(url) => Ok(to_value(url).unwrap()),
  52. Err(_) => Err(format!("Could not resolve URL for link `{}` not found.", v).into())
  53. },
  54. Err(_) => Err(format!("`get_url` received link={:?} but it requires a string", val).into()),
  55. },
  56. None => Err("`get_url` requires a `link` argument.".into()),
  57. }
  58. })
  59. }