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.

120 lines
4.1KB

  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, sort_pages};
  10. #[derive(Clone, Debug, PartialEq)]
  11. pub struct Section {
  12. /// The _index.md full path
  13. pub file_path: PathBuf,
  14. /// The .md path, starting from the content directory, with / slashes
  15. pub relative_path: String,
  16. /// Path of the directory containing the _index.md file
  17. pub parent_path: PathBuf,
  18. /// The folder names from `content` to this section file
  19. pub components: Vec<String>,
  20. /// The URL path of the page
  21. pub path: String,
  22. /// The full URL for that page
  23. pub permalink: String,
  24. /// The front matter meta-data
  25. pub meta: FrontMatter,
  26. /// All direct pages of that section
  27. pub pages: Vec<Page>,
  28. /// All direct subsections
  29. pub subsections: Vec<Section>,
  30. }
  31. impl Section {
  32. pub fn new<P: AsRef<Path>>(file_path: P, meta: FrontMatter) -> Section {
  33. let file_path = file_path.as_ref();
  34. Section {
  35. file_path: file_path.to_path_buf(),
  36. relative_path: "".to_string(),
  37. parent_path: file_path.parent().unwrap().to_path_buf(),
  38. components: vec![],
  39. path: "".to_string(),
  40. permalink: "".to_string(),
  41. meta: meta,
  42. pages: vec![],
  43. subsections: vec![],
  44. }
  45. }
  46. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  47. let (meta, _) = split_content(file_path, content)?;
  48. let mut section = Section::new(file_path, meta);
  49. section.components = find_content_components(&section.file_path);
  50. section.path = section.components.join("/");
  51. section.permalink = config.make_permalink(&section.path);
  52. if section.components.len() == 0 {
  53. section.relative_path = "_index.md".to_string();
  54. } else {
  55. section.relative_path = format!("{}/_index.md", section.components.join("/"));
  56. }
  57. Ok(section)
  58. }
  59. /// Read and parse a .md file into a Page struct
  60. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  61. let path = path.as_ref();
  62. let content = read_file(path)?;
  63. Section::parse(path, &content, config)
  64. }
  65. pub fn get_template_name(&self) -> String {
  66. match self.meta.template {
  67. Some(ref l) => l.to_string(),
  68. None => {
  69. if self.is_index() {
  70. return "index.html".to_string();
  71. }
  72. "section.html".to_string()
  73. },
  74. }
  75. }
  76. /// Renders the page using the default layout, unless specified in front-matter
  77. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  78. let tpl_name = self.get_template_name();
  79. let mut context = Context::new();
  80. context.add("config", config);
  81. context.add("section", self);
  82. context.add("current_url", &self.permalink);
  83. context.add("current_path", &self.path);
  84. tera.render(&tpl_name, &context)
  85. .chain_err(|| format!("Failed to render section '{}'", self.file_path.display()))
  86. }
  87. pub fn is_index(&self) -> bool {
  88. self.components.len() == 0
  89. }
  90. }
  91. impl ser::Serialize for Section {
  92. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  93. let mut state = serializer.serialize_struct("section", 6)?;
  94. state.serialize_field("title", &self.meta.title)?;
  95. state.serialize_field("description", &self.meta.description)?;
  96. state.serialize_field("path", &format!("/{}", self.path))?;
  97. state.serialize_field("permalink", &self.permalink)?;
  98. let (sorted_pages, _) = sort_pages(self.pages.clone(), Some(self));
  99. state.serialize_field("pages", &sorted_pages)?;
  100. state.serialize_field("subsections", &self.subsections)?;
  101. state.end()
  102. }
  103. }