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.

131 lines
3.9KB

  1. use std::collections::HashMap;
  2. use regex::Regex;
  3. use tera::{Tera, Context};
  4. use errors::{Result, ResultExt};
  5. lazy_static!{
  6. pub static ref SHORTCODE_RE: Regex = Regex::new(r#"\{(?:%|\{)\s+([[:word:]]+?)\(([[:word:]]+?="?.+?"?)?\)\s+(?:%|\})\}"#).unwrap();
  7. }
  8. /// A shortcode that has a body
  9. /// Called by having some content like {% ... %} body {% end %}
  10. /// We need the struct to hold the data while we're processing the markdown
  11. #[derive(Debug)]
  12. pub struct ShortCode {
  13. name: String,
  14. args: HashMap<String, String>,
  15. body: String,
  16. }
  17. impl ShortCode {
  18. pub fn new(name: &str, args: HashMap<String, String>) -> ShortCode {
  19. ShortCode {
  20. name: name.to_string(),
  21. args: args,
  22. body: String::new(),
  23. }
  24. }
  25. pub fn append(&mut self, text: &str) {
  26. self.body.push_str(text)
  27. }
  28. pub fn render(&self, tera: &Tera) -> Result<String> {
  29. let mut context = Context::new();
  30. for (key, value) in &self.args {
  31. context.add(key, value);
  32. }
  33. context.add("body", &self.body);
  34. let tpl_name = format!("shortcodes/{}.html", self.name);
  35. tera.render(&tpl_name, &context)
  36. .chain_err(|| format!("Failed to render {} shortcode", self.name))
  37. }
  38. }
  39. /// Parse a shortcode without a body
  40. pub fn parse_shortcode(input: &str) -> (String, HashMap<String, String>) {
  41. let mut args = HashMap::new();
  42. let caps = SHORTCODE_RE.captures(input).unwrap();
  43. // caps[0] is the full match
  44. let name = &caps[1];
  45. if let Some(arg_list) = caps.get(2) {
  46. for arg in arg_list.as_str().split(',') {
  47. let bits = arg.split('=').collect::<Vec<_>>();
  48. args.insert(bits[0].trim().to_string(), bits[1].replace("\"", ""));
  49. }
  50. }
  51. (name.to_string(), args)
  52. }
  53. /// Renders a shortcode or return an error
  54. pub fn render_simple_shortcode(tera: &Tera, name: &str, args: &HashMap<String, String>) -> Result<String> {
  55. let mut context = Context::new();
  56. for (key, value) in args.iter() {
  57. context.add(key, value);
  58. }
  59. let tpl_name = format!("shortcodes/{}.html", name);
  60. tera.render(&tpl_name, &context).chain_err(|| format!("Failed to render {} shortcode", name))
  61. }
  62. #[cfg(test)]
  63. mod tests {
  64. use super::{parse_shortcode, SHORTCODE_RE};
  65. #[test]
  66. fn can_match_all_kinds_of_shortcode() {
  67. let inputs = vec![
  68. "{{ basic() }}",
  69. "{{ basic(ho=1) }}",
  70. "{{ basic(ho=\"hey\") }}",
  71. "{{ basic(ho=\"hey_underscore\") }}",
  72. "{{ basic(ho=\"hey-dash\") }}",
  73. "{% basic(ho=\"hey-dash\") %}",
  74. "{% basic(ho=\"hey_underscore\") %}",
  75. "{% basic() %}",
  76. "{% quo_te(author=\"Bob\") %}",
  77. "{{ quo_te(author=\"Bob\") }}",
  78. ];
  79. for i in inputs {
  80. println!("{}", i);
  81. assert!(SHORTCODE_RE.is_match(i));
  82. }
  83. }
  84. #[test]
  85. fn can_parse_simple_shortcode_no_arg() {
  86. let (name, args) = parse_shortcode(r#"{{ basic() }}"#);
  87. assert_eq!(name, "basic");
  88. assert!(args.is_empty());
  89. }
  90. #[test]
  91. fn can_parse_simple_shortcode_one_arg() {
  92. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc") }}"#);
  93. assert_eq!(name, "youtube");
  94. assert_eq!(args["id"], "w7Ft2ymGmfc");
  95. }
  96. #[test]
  97. fn can_parse_simple_shortcode_several_arg() {
  98. let (name, args) = parse_shortcode(r#"{{ youtube(id="w7Ft2ymGmfc", autoplay=true) }}"#);
  99. assert_eq!(name, "youtube");
  100. assert_eq!(args["id"], "w7Ft2ymGmfc");
  101. assert_eq!(args["autoplay"], "true");
  102. }
  103. #[test]
  104. fn can_parse_block_shortcode_several_arg() {
  105. let (name, args) = parse_shortcode(r#"{% youtube(id="w7Ft2ymGmfc", autoplay=true) %}"#);
  106. assert_eq!(name, "youtube");
  107. assert_eq!(args["id"], "w7Ft2ymGmfc");
  108. assert_eq!(args["autoplay"], "true");
  109. }
  110. }