|
| 1 | +/// Formatting filters for MiniJinja templates |
| 2 | +use minijinja::Value; |
| 3 | +use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode}; |
| 4 | + |
| 5 | +/// Format file size in human-readable format (bytes, KB, MB, GB, etc.) |
| 6 | +/// |
| 7 | +/// # Arguments |
| 8 | +/// |
| 9 | +/// * `value` - The file size in bytes (as number) |
| 10 | +/// |
| 11 | +/// # Example |
| 12 | +/// |
| 13 | +/// ```jinja |
| 14 | +/// {{ 1024 | filesizeformat }} => "1 KB" |
| 15 | +/// {{ 1048576 | filesizeformat }} => "1 MB" |
| 16 | +/// ``` |
| 17 | +pub fn filesizeformat_filter(value: &Value) -> Result<String, minijinja::Error> { |
| 18 | + let bytes = if let Some(n) = value.as_i64() { |
| 19 | + n as f64 |
| 20 | + } else { |
| 21 | + return Err(minijinja::Error::new( |
| 22 | + minijinja::ErrorKind::InvalidOperation, |
| 23 | + "filesizeformat filter requires a number", |
| 24 | + )); |
| 25 | + }; |
| 26 | + |
| 27 | + const UNITS: &[&str] = &["bytes", "KB", "MB", "GB", "TB", "PB"]; |
| 28 | + const THRESHOLD: f64 = 1024.0; |
| 29 | + |
| 30 | + if bytes < THRESHOLD { |
| 31 | + return Ok(format!("{} bytes", bytes as i64)); |
| 32 | + } |
| 33 | + |
| 34 | + let mut size = bytes; |
| 35 | + let mut unit_index = 0; |
| 36 | + |
| 37 | + while size >= THRESHOLD && unit_index < UNITS.len() - 1 { |
| 38 | + size /= THRESHOLD; |
| 39 | + unit_index += 1; |
| 40 | + } |
| 41 | + |
| 42 | + // Format with appropriate precision |
| 43 | + // If it's a whole number (or very close to one), show without decimals |
| 44 | + if (size - size.round()).abs() < 0.01 { |
| 45 | + Ok(format!("{:.0} {}", size, UNITS[unit_index])) |
| 46 | + } else if size < 10.0 { |
| 47 | + Ok(format!("{:.2} {}", size, UNITS[unit_index])) |
| 48 | + } else if size < 100.0 { |
| 49 | + Ok(format!("{:.1} {}", size, UNITS[unit_index])) |
| 50 | + } else { |
| 51 | + Ok(format!("{:.0} {}", size, UNITS[unit_index])) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// URL encode a string - encode special characters for use in URLs |
| 56 | +/// |
| 57 | +/// # Arguments |
| 58 | +/// |
| 59 | +/// * `value` - The string to URL encode |
| 60 | +/// |
| 61 | +/// # Example |
| 62 | +/// |
| 63 | +/// ```jinja |
| 64 | +/// {{ "hello world & foo=bar" | urlencode }} => "hello%20world%20%26%20foo%3Dbar" |
| 65 | +/// ``` |
| 66 | +pub fn urlencode_filter(value: &Value) -> Result<String, minijinja::Error> { |
| 67 | + let s = value.as_str().ok_or_else(|| { |
| 68 | + minijinja::Error::new( |
| 69 | + minijinja::ErrorKind::InvalidOperation, |
| 70 | + "urlencode filter requires a string", |
| 71 | + ) |
| 72 | + })?; |
| 73 | + |
| 74 | + Ok(utf8_percent_encode(s, NON_ALPHANUMERIC).to_string()) |
| 75 | +} |
0 commit comments