Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix partially formatted if chains in attributes #2999

Merged
merged 1 commit into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/core/tests/conditional_formatted_attributes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use dioxus::prelude::*;

/// Make sure that rsx! handles conditional attributes with one formatted branch correctly
/// Regression test for https://github.com/DioxusLabs/dioxus/issues/2997
#[test]
fn partially_formatted_conditional_attribute() {
let width = "1px";
_ = rsx! {
div {
width: if true { "{width}" } else { "100px" }
}
};
}
15 changes: 15 additions & 0 deletions packages/rsx/src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,20 @@ impl IfAttributeValue {
then_value,
else_value,
} = self;

// Quote an attribute value and convert the value to a string if it is formatted
// We always quote formatted segments as strings inside if statements so they have a consistent type
// This fixes https://github.com/DioxusLabs/dioxus/issues/2997
fn quote_attribute_value_string(value: &AttributeValue) -> TokenStream2 {
if matches!(value, AttributeValue::AttrLiteral(HotLiteral::Fmted(_))) {
quote! { #value.to_string() }
} else {
value.to_token_stream()
}
}

let then_value = quote_attribute_value_string(then_value);

let then_value = if terminated {
quote! { #then_value }
}
Expand All @@ -630,6 +644,7 @@ impl IfAttributeValue {
tokens
}
Some(other) => {
let other = quote_attribute_value_string(other);
if terminated {
quote! { #other }
} else {
Expand Down
Loading