Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use tera::Tera;
- fn main() {
- let mut urls: HashMap<String, String> = HashMap::new();
- let mut tera = match Tera::new("templates/**/*.html") {
- Ok(t) => t,
- Err(e) => {
- println!("Parsing error(s): {}", e);
- ::std::process::exit(1);
- }
- };
- urls.insert("home".to_string(), "http://address.com/home".to_string());
- //Register our function here with External types
- tera.register_function("url_for", make_url(urls));
- }
- fn make_url(urls: HashMap<String, String>) -> impl Function {
- //Boxed closure for Function
- Box::new(
- move |args: &HashMap<String, Value>| -> Result<Value, tera::Error> {
- //cloning the urls otherwise it needs to be a &'static
- let urls = urls.clone();
- //getting the name argument from the args list which is returned by tera
- let name = args
- .get("name")
- .ok_or_else(|| tera::Error::msg("`name` must Exist in url_for"))?
- .as_str()
- .ok_or_else(|| tera::Error::msg("`name` must be a string in url_for"))?
- .trim();
- //getting our url from out urls hashmap.
- let url = urls
- .get(&name.to_string())
- .ok_or_else(|| tera::Error::msg(format!("`{}` is not a valid url", name)))?
- .as_str();
- //Transforming url into json string value.
- let value = to_value(url)
- .map_err(|_| tera::Error::msg("failed to convert url to json value"))?;
- Ok(value)
- },
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement