Skip to content

Instantly share code, notes, and snippets.

@boyswan
Created June 28, 2024 14:04
Show Gist options
  • Save boyswan/39db4018a085ad4da59a2e327d949a94 to your computer and use it in GitHub Desktop.
Save boyswan/39db4018a085ad4da59a2e327d949a94 to your computer and use it in GitHub Desktop.
Tailwind logic macro
#[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()
}
}};
}
@boyswan
Copy link
Author

boyswan commented Jun 28, 2024

Macro to allow static, dynamic and conditional concatination

  tw!(
    "w-full h-full";
    is_active => "text-blue-500", "text-gray-500";
    has_bg => "bg-green-100";
  )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment