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.

59 lines
1.7 KiB

3 years ago
  1. use actix_web::HttpRequest;
  2. use askama::Template;
  3. use crate::config::Config;
  4. #[derive(Template)]
  5. #[template(path = "index.html")]
  6. pub struct TplIndex<'a> {
  7. pub lang: &'a str,
  8. pub csrf_token: &'a str,
  9. }
  10. #[derive(Template)]
  11. #[template(path = "error.html")]
  12. pub struct TplError<'a> {
  13. pub lang: &'a str,
  14. pub error_msg: &'a str,
  15. }
  16. #[derive(Template)]
  17. #[template(path = "link.html")]
  18. pub struct TplLink<'a> {
  19. pub lang: &'a str,
  20. pub admin_token: &'a str,
  21. pub config: &'a Config,
  22. }
  23. pub fn get_lang(req: &HttpRequest) -> String {
  24. // getting language from client header
  25. // taking the two first characters of the Accept-Language header,
  26. // in lowercase, then parsing it.
  27. // if it fails, returns "en"
  28. if let Some(l) = req.headers().get("Accept-Language") {
  29. if let Ok(s) = l.to_str() {
  30. return s.to_lowercase()[..2].to_string();
  31. }
  32. }
  33. String::from("en")
  34. }
  35. mod filters {
  36. use crate::config::LOC;
  37. pub fn tr(key: &str, lang: &str) -> askama::Result<String> {
  38. let translation = LOC.get(key).ok_or_else(|| {
  39. eprintln!("tr filter: couldn't find the key {}", key);
  40. askama::Error::from(std::fmt::Error)
  41. })?;
  42. Ok(String::from(
  43. translation
  44. .get(lang)
  45. .unwrap_or(translation.get("en").ok_or_else(|| {
  46. eprintln!("tr filter: couldn't find the lang {} in key {}", lang, key);
  47. askama::Error::from(std::fmt::Error)
  48. })?)
  49. .as_str()
  50. .ok_or_else(|| {
  51. eprintln!("tr filter: lang {} in key {} is not str", lang, key);
  52. askama::Error::from(std::fmt::Error)
  53. })?,
  54. ))
  55. }
  56. }