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.4KB

  1. use tera::{Tera, Context};
  2. use errors::Result;
  3. /// Renders the given template with the given context, but also ensures that, if the default file
  4. /// is not found, it will look up for the equivalent template for the current theme if there is one.
  5. /// Lastly, if it's a default template (index, section or page), it will just return an empty string
  6. /// to avoid an error if there isn't a template with that name
  7. pub fn render_template(name: &str, tera: &Tera, context: &Context, theme: Option<String>) -> Result<String> {
  8. if tera.templates.contains_key(name) {
  9. return tera
  10. .render(name, context)
  11. .map_err(|e| e.into());
  12. }
  13. if let Some(ref t) = theme {
  14. return tera
  15. .render(&format!("{}/templates/{}", t, name), context)
  16. .map_err(|e| e.into());
  17. }
  18. if name == "index.html" || name == "section.html" || name == "page.html" {
  19. return Ok(String::new());
  20. }
  21. bail!("Tried to render `{}` but the template wasn't found", name)
  22. }
  23. /// Rewrites the path from extend/macros of the theme used to ensure
  24. /// that they will point to the right place (theme/templates/...)
  25. /// Include is NOT supported as it would be a pain to add and using blocks
  26. /// or macros is always better anyway for themes
  27. pub fn rewrite_theme_paths(tera: &mut Tera, theme: &str) {
  28. // We want to match the paths in the templates to the new names
  29. for tpl in tera.templates.values_mut() {
  30. // First the parent if there is none
  31. if let Some(ref p) = tpl.parent.clone() {
  32. tpl.parent = Some(format!("{}/templates/{}", theme, p));
  33. }
  34. // Next the macros import
  35. let mut updated = vec![];
  36. for &(ref filename, ref namespace) in &tpl.imported_macro_files {
  37. updated.push((format!("{}/templates/{}", theme, filename), namespace.to_string()));
  38. }
  39. tpl.imported_macro_files = updated;
  40. }
  41. }
  42. #[cfg(test)]
  43. mod tests {
  44. use tera::Tera;
  45. use super::{rewrite_theme_paths};
  46. #[test]
  47. fn can_rewrite_all_paths_of_theme() {
  48. let mut tera = Tera::parse("templates/*.html").unwrap();
  49. rewrite_theme_paths(&mut tera, "hyde");
  50. // special case to make the test work: we also rename the files to
  51. // match the imports
  52. for (key, val) in tera.templates.clone() {
  53. tera.templates.insert(format!("hyde/templates/{}", key), val.clone());
  54. }
  55. tera.build_inheritance_chains().unwrap();
  56. }
  57. }