Created
June 28, 2024 14:04
-
-
Save boyswan/39db4018a085ad4da59a2e327d949a94 to your computer and use it in GitHub Desktop.
Tailwind logic macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_export] | |
macro_rules! tw { | |
// Base case: when there are no tokens left, return an empty string. | |
() => (String::new()); | |
// New case: handle static string literals | |
($static:literal ; $($rest:tt)*) => {{ | |
let mut class = String::from($static); | |
let rest_classes = tw!($($rest)*); | |
if !rest_classes.is_empty() { | |
class.push_str(" "); | |
} | |
class.push_str(&rest_classes); | |
class | |
}}; | |
// Case with a condition, a true class, and an optional false class, all followed by more tokens. | |
($cond:expr => $true_class:expr $( , $false_class:expr )? ; $($rest:tt)*) => {{ | |
let mut class = String::new(); | |
if $cond { | |
class.push_str($true_class); | |
} else { | |
$( class.push_str($false_class); )? | |
} | |
// Recursively process any remaining tokens, ensuring we separate classes with a space if needed. | |
let rest_classes = tw!($($rest)*); | |
if !class.is_empty() && !rest_classes.is_empty() { | |
class.push_str(" "); | |
} | |
class.push_str(&rest_classes); | |
class | |
}}; | |
// Case with a condition and a true class, without a false class and without more tokens. | |
($cond:expr => $true_class:expr) => {{ | |
if $cond { | |
$true_class.to_string() | |
} else { | |
String::new() | |
} | |
}}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Macro to allow static, dynamic and conditional concatination