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.

102 lines
3.4KB

  1. use std::path::{Path, PathBuf};
  2. use std::result::Result as StdResult;
  3. use tera::{Tera, Context};
  4. use serde::ser::{SerializeStruct, self};
  5. use config::Config;
  6. use front_matter::{FrontMatter, split_content};
  7. use errors::{Result, ResultExt};
  8. use utils::{read_file, find_content_components};
  9. use page::Page;
  10. #[derive(Clone, Debug, PartialEq)]
  11. pub struct Section {
  12. /// The _index.md full path
  13. pub file_path: PathBuf,
  14. /// Path of the directory containing the _index.md file
  15. pub parent_path: PathBuf,
  16. /// The folder names from `content` to this section file
  17. pub components: Vec<String>,
  18. /// The relative URL of the page
  19. pub url: String,
  20. /// The full URL for that page
  21. pub permalink: String,
  22. /// The front matter meta-data
  23. pub meta: FrontMatter,
  24. /// All direct pages of that section
  25. pub pages: Vec<Page>,
  26. /// All direct subsections
  27. pub subsections: Vec<Section>,
  28. }
  29. impl Section {
  30. pub fn new(file_path: &Path, meta: FrontMatter) -> Section {
  31. Section {
  32. file_path: file_path.to_path_buf(),
  33. parent_path: file_path.parent().unwrap().to_path_buf(),
  34. components: vec![],
  35. url: "".to_string(),
  36. permalink: "".to_string(),
  37. meta: meta,
  38. pages: vec![],
  39. subsections: vec![],
  40. }
  41. }
  42. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  43. let (meta, _) = split_content(file_path, content)?;
  44. let mut section = Section::new(file_path, meta);
  45. section.components = find_content_components(&section.file_path);
  46. section.url = section.components.join("/");
  47. section.permalink = section.components.join("/");
  48. section.permalink = if config.base_url.ends_with('/') {
  49. format!("{}{}", config.base_url, section.url)
  50. } else {
  51. format!("{}/{}", config.base_url, section.url)
  52. };
  53. Ok(section)
  54. }
  55. /// Read and parse a .md file into a Page struct
  56. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  57. let path = path.as_ref();
  58. let content = read_file(path)?;
  59. Section::parse(path, &content, config)
  60. }
  61. /// Renders the page using the default layout, unless specified in front-matter
  62. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  63. let tpl_name = match self.meta.template {
  64. Some(ref l) => l.to_string(),
  65. None => "section.html".to_string()
  66. };
  67. // TODO: create a helper to create context to ensure all contexts
  68. // have the same names
  69. let mut context = Context::new();
  70. context.add("config", config);
  71. context.add("section", self);
  72. tera.render(&tpl_name, &context)
  73. .chain_err(|| format!("Failed to render section '{}'", self.file_path.display()))
  74. }
  75. }
  76. impl ser::Serialize for Section {
  77. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  78. let mut state = serializer.serialize_struct("section", 6)?;
  79. state.serialize_field("title", &self.meta.title)?;
  80. state.serialize_field("description", &self.meta.description)?;
  81. state.serialize_field("url", &format!("/{}", self.url))?;
  82. state.serialize_field("permalink", &self.permalink)?;
  83. state.serialize_field("pages", &self.pages)?;
  84. state.serialize_field("subsections", &self.subsections)?;
  85. state.end()
  86. }
  87. }