Advertisement
Guest User

Tera Function Add

a guest
Sep 21st, 2021
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.56 KB | None | 0 0
  1. use tera::Tera;
  2.  
  3. fn main() {
  4.     let mut urls: HashMap<String, String> = HashMap::new();
  5.     let mut tera = match Tera::new("templates/**/*.html") {
  6.         Ok(t) => t,
  7.         Err(e) => {
  8.             println!("Parsing error(s): {}", e);
  9.             ::std::process::exit(1);
  10.         }
  11.     };
  12.  
  13.     urls.insert("home".to_string(), "http://address.com/home".to_string());
  14.  
  15.     //Register our function here with External types
  16.     tera.register_function("url_for", make_url(urls));
  17. }
  18.  
  19. fn make_url(urls: HashMap<String, String>) -> impl Function {
  20.     //Boxed closure for Function
  21.     Box::new(
  22.         move |args: &HashMap<String, Value>| -> Result<Value, tera::Error> {
  23.             //cloning the urls otherwise it needs to be a &'static
  24.             let urls = urls.clone();
  25.             //getting the name argument from the args list which is returned by tera
  26.             let name = args
  27.                 .get("name")
  28.                 .ok_or_else(|| tera::Error::msg("`name` must Exist in url_for"))?
  29.                 .as_str()
  30.                 .ok_or_else(|| tera::Error::msg("`name` must be a string in url_for"))?
  31.                 .trim();
  32.             //getting our url from out urls hashmap.
  33.             let url = urls
  34.                 .get(&name.to_string())
  35.                 .ok_or_else(|| tera::Error::msg(format!("`{}` is not a valid url", name)))?
  36.                 .as_str();
  37.             //Transforming url into json string value.
  38.             let value = to_value(url)
  39.                 .map_err(|_| tera::Error::msg("failed to convert url to json value"))?;
  40.             Ok(value)
  41.         },
  42.     )
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement