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.

pagination.rs 8.9KB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. use std::collections::HashMap;
  2. use tera::{Context, to_value, Value};
  3. use errors::{Result, ResultExt};
  4. use content::{Page, Section};
  5. use site::Site;
  6. /// A list of all the pages in the paginator with their index and links
  7. #[derive(Clone, Debug, PartialEq, Serialize)]
  8. pub struct Pager<'a> {
  9. /// The page number in the paginator (1-indexed)
  10. index: usize,
  11. /// Permalink to that page
  12. permalink: String,
  13. /// Path to that page
  14. path: String,
  15. /// All pages for the pager
  16. pages: Vec<&'a Page>
  17. }
  18. impl<'a> Pager<'a> {
  19. fn new(index: usize, pages: Vec<&'a Page>, permalink: String, path: String) -> Pager<'a> {
  20. Pager {
  21. index,
  22. permalink,
  23. path,
  24. pages,
  25. }
  26. }
  27. }
  28. #[derive(Clone, Debug, PartialEq)]
  29. pub struct Paginator<'a> {
  30. /// All pages in the section
  31. all_pages: &'a [Page],
  32. /// Pages split in chunks of `paginate_by`
  33. pub pagers: Vec<Pager<'a>>,
  34. /// How many content pages on a paginated page at max
  35. paginate_by: usize,
  36. /// The section struct we're building the paginator for
  37. section: &'a Section,
  38. }
  39. impl<'a> Paginator<'a> {
  40. /// Create a new paginator
  41. /// It will always at least create one pager (the first) even if there are no pages to paginate
  42. pub fn new(all_pages: &'a [Page], section: &'a Section) -> Paginator<'a> {
  43. let paginate_by = section.meta.paginate_by.unwrap();
  44. let paginate_path = match section.meta.paginate_path {
  45. Some(ref p) => p,
  46. None => unreachable!(),
  47. };
  48. let mut pages = vec![];
  49. let mut current_page = vec![];
  50. for page in all_pages {
  51. current_page.push(page);
  52. if current_page.len() == paginate_by {
  53. pages.push(current_page);
  54. current_page = vec![];
  55. }
  56. }
  57. if !current_page.is_empty() {
  58. pages.push(current_page);
  59. }
  60. let mut pagers = vec![];
  61. for (index, page) in pages.iter().enumerate() {
  62. // First page has no pagination path
  63. if index == 0 {
  64. pagers.push(Pager::new(1, page.clone(), section.permalink.clone(), section.path.clone()));
  65. continue;
  66. }
  67. let page_path = format!("{}/{}", paginate_path, index + 1);
  68. let permalink = if section.permalink.ends_with('/') {
  69. format!("{}{}", section.permalink, page_path)
  70. } else {
  71. format!("{}/{}", section.permalink, page_path)
  72. };
  73. pagers.push(Pager::new(
  74. index + 1,
  75. page.clone(),
  76. permalink,
  77. if section.is_index() { page_path } else { format!("{}/{}", section.path, page_path) }
  78. ));
  79. }
  80. // We always have the index one at least
  81. if pagers.is_empty() {
  82. pagers.push(Pager::new(1, vec![], section.permalink.clone(), section.path.clone()));
  83. }
  84. Paginator {
  85. all_pages: all_pages,
  86. pagers: pagers,
  87. paginate_by: paginate_by,
  88. section: section,
  89. }
  90. }
  91. pub fn build_paginator_context(&self, current_pager: &Pager) -> HashMap<&str, Value> {
  92. let mut paginator = HashMap::new();
  93. // the pager index is 1-indexed so we want a 0-indexed one for indexing there
  94. let pager_index = current_pager.index - 1;
  95. // Global variables
  96. paginator.insert("paginate_by", to_value(self.paginate_by).unwrap());
  97. paginator.insert("first", to_value(&self.section.permalink).unwrap());
  98. let last_pager = &self.pagers[self.pagers.len() - 1];
  99. paginator.insert("last", to_value(&last_pager.permalink).unwrap());
  100. paginator.insert("pagers", to_value(&self.pagers).unwrap());
  101. // Variables for this specific page
  102. if pager_index > 0 {
  103. let prev_pager = &self.pagers[pager_index - 1];
  104. paginator.insert("previous", to_value(&prev_pager.permalink).unwrap());
  105. } else {
  106. paginator.insert("previous", to_value::<Option<()>>(None).unwrap());
  107. }
  108. if pager_index < self.pagers.len() - 1 {
  109. let next_pager = &self.pagers[pager_index + 1];
  110. paginator.insert("next", to_value(&next_pager.permalink).unwrap());
  111. } else {
  112. paginator.insert("next", to_value::<Option<()>>(None).unwrap());
  113. }
  114. paginator.insert("pages", to_value(&current_pager.pages).unwrap());
  115. paginator.insert("current_index", to_value(current_pager.index).unwrap());
  116. paginator
  117. }
  118. pub fn render_pager(&self, pager: &Pager, site: &Site) -> Result<String> {
  119. let mut context = Context::new();
  120. context.add("config", &site.config);
  121. context.add("section", self.section);
  122. context.add("current_url", &pager.permalink);
  123. context.add("current_path", &pager.path);
  124. context.add("paginator", &self.build_paginator_context(pager));
  125. if self.section.is_index() {
  126. context.add("section", &site.sections);
  127. }
  128. site.tera.render(&self.section.get_template_name(), &context)
  129. .chain_err(|| format!("Failed to render pager {} of section '{}'", pager.index, self.section.file.path.display()))
  130. }
  131. }
  132. #[cfg(test)]
  133. mod tests {
  134. use tera::{to_value};
  135. use front_matter::SectionFrontMatter;
  136. use content::{Page, Section};
  137. use super::{Paginator};
  138. fn create_section(is_index: bool) -> Section {
  139. let mut f = SectionFrontMatter::default();
  140. f.paginate_by = Some(2);
  141. f.paginate_path = Some("page".to_string());
  142. let mut s = Section::new("content/_index.md", f);
  143. if !is_index {
  144. s.path = "posts".to_string();
  145. s.permalink = "https://vincent.is/posts".to_string();
  146. s.file.components = vec!["posts".to_string()];
  147. } else {
  148. s.permalink = "https://vincent.is".to_string();
  149. }
  150. s
  151. }
  152. #[test]
  153. fn test_can_create_paginator() {
  154. let pages = vec![
  155. Page::default(),
  156. Page::default(),
  157. Page::default(),
  158. ];
  159. let section = create_section(false);
  160. let paginator = Paginator::new(pages.as_slice(), &section);
  161. assert_eq!(paginator.pagers.len(), 2);
  162. assert_eq!(paginator.pagers[0].index, 1);
  163. assert_eq!(paginator.pagers[0].pages.len(), 2);
  164. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is/posts");
  165. assert_eq!(paginator.pagers[0].path, "posts");
  166. assert_eq!(paginator.pagers[1].index, 2);
  167. assert_eq!(paginator.pagers[1].pages.len(), 1);
  168. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/posts/page/2");
  169. assert_eq!(paginator.pagers[1].path, "posts/page/2");
  170. }
  171. #[test]
  172. fn test_can_create_paginator_for_index() {
  173. let pages = vec![
  174. Page::default(),
  175. Page::default(),
  176. Page::default(),
  177. ];
  178. let section = create_section(true);
  179. let paginator = Paginator::new(pages.as_slice(), &section);
  180. assert_eq!(paginator.pagers.len(), 2);
  181. assert_eq!(paginator.pagers[0].index, 1);
  182. assert_eq!(paginator.pagers[0].pages.len(), 2);
  183. assert_eq!(paginator.pagers[0].permalink, "https://vincent.is");
  184. assert_eq!(paginator.pagers[0].path, "");
  185. assert_eq!(paginator.pagers[1].index, 2);
  186. assert_eq!(paginator.pagers[1].pages.len(), 1);
  187. assert_eq!(paginator.pagers[1].permalink, "https://vincent.is/page/2");
  188. assert_eq!(paginator.pagers[1].path, "page/2");
  189. }
  190. #[test]
  191. fn test_can_build_paginator_context() {
  192. let pages = vec![
  193. Page::default(),
  194. Page::default(),
  195. Page::default(),
  196. ];
  197. let section = create_section(false);
  198. let paginator = Paginator::new(pages.as_slice(), &section);
  199. assert_eq!(paginator.pagers.len(), 2);
  200. let context = paginator.build_paginator_context(&paginator.pagers[0]);
  201. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  202. assert_eq!(context["first"], to_value("https://vincent.is/posts").unwrap());
  203. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2").unwrap());
  204. assert_eq!(context["previous"], to_value::<Option<()>>(None).unwrap());
  205. assert_eq!(context["next"], to_value("https://vincent.is/posts/page/2").unwrap());
  206. assert_eq!(context["current_index"], to_value(1).unwrap());
  207. let context = paginator.build_paginator_context(&paginator.pagers[1]);
  208. assert_eq!(context["paginate_by"], to_value(2).unwrap());
  209. assert_eq!(context["first"], to_value("https://vincent.is/posts").unwrap());
  210. assert_eq!(context["last"], to_value("https://vincent.is/posts/page/2").unwrap());
  211. assert_eq!(context["next"], to_value::<Option<()>>(None).unwrap());
  212. assert_eq!(context["previous"], to_value("https://vincent.is/posts").unwrap());
  213. assert_eq!(context["current_index"], to_value(2).unwrap());
  214. }
  215. }