diff --git a/docs/docs/views/templates/functions/string.md b/docs/docs/views/templates/functions/string.md index fc4e9cbe..247c4436 100644 --- a/docs/docs/views/templates/functions/string.md +++ b/docs/docs/views/templates/functions/string.md @@ -174,3 +174,16 @@ This method accepts all data types, but it does convert them to their string rep ``` 1 two three ``` + +### `title` + +Converts the string to "Title Case" formatting. + +=== "Template" + ```erb + <%= "hello world".title %> + ``` +=== "Output" + ``` + Hello World + ``` diff --git a/rwf/src/lib.rs b/rwf/src/lib.rs index cdcb3c97..4ccf0acb 100644 --- a/rwf/src/lib.rs +++ b/rwf/src/lib.rs @@ -138,6 +138,16 @@ pub fn capitalize(string: &str) -> String { uppercase } +/// Convert string to title case. +pub fn title_case(string: &str) -> String { + string + .split(" ") + .into_iter() + .map(|s| capitalize(s)) + .collect::>() + .join(" ") +} + /// Convert string to PascalCase (often confused with camelCase). pub fn pascal_case(string: &str) -> String { string diff --git a/rwf/src/view/template/lexer/value.rs b/rwf/src/view/template/lexer/value.rs index 25017f85..58e91751 100644 --- a/rwf/src/view/template/lexer/value.rs +++ b/rwf/src/view/template/lexer/value.rs @@ -261,6 +261,7 @@ impl Value { "capitalize" => Value::String(crate::capitalize(&value)), "camelize" | "to_PascalCase" => Value::String(crate::pascal_case(&value)), "underscore" | "to_snake_case" => Value::String(crate::snake_case(&value)), + "title" => Value::String(crate::title_case(&value)), "urlencode" => Value::String(crate::http::urlencode(&value)), "urldecode" => Value::String(crate::http::urldecode(&value)), "len" => Value::Integer(value.len() as i64), @@ -719,4 +720,12 @@ mod test { .unwrap(); assert_eq!(v, Value::String("Hey Alice, this is Alice".into())); } + + #[test] + fn test_title_case() { + let v = Value::String("hello world, how are you?".into()) + .call("title", &[], &Context::default()) + .unwrap(); + assert_eq!(v, Value::String("Hello World, How Are You?".into())) + } }