chanan / BlazorStyled

CSS in Blazor Components
https://blazorstyled.io
The Unlicense
191 stars 19 forks source link

Add if/then support? #87

Open VR-Architect opened 4 years ago

VR-Architect commented 4 years ago

Hey, your tools is quickly becoming my good friend and love it. I came across a scenario you may consider adding? Can we get the ability to use if/then statements

`

.nav-item:hover { @if (IsGradiant) { background: linear-gradient(to bottom, @props.HoverStyle.Color2 0%, @props.HoverStyle.Color1 100%); } else { background-color: @props.HoverStyle.Color1; } }

`

chanan commented 4 years ago

Hi!

Glad you are liking BlazorStyled!

I am on the mobile right so can’t try it, but here are a few thoughts: (when I get to the computer I will try it out)

  1. Off hand it looks like it should work - ultimately the Styled tag grabs the stuff inside of it as a string. From the examples on the site we can see that simple variables work (color white on the home page example)

  2. If it does not work, chances of me getting that syntax to work is slim (not 0 but close to it)

  3. Have you tried Compose? I think that will do what you want. Check the site under composition. But basically Compose and ComposeIf will append a (dynamically created) class to the return value of @bind-Classname. And I think you can do what you want with that. The only draw back is that it would only work for dynamic classes and it looks like from your example you are using static ones so it might not work for your case.

Anyway, I will check your example out when I get to the computer today.

PS - if your project is a public one and you want to add it to the BlazorStyled docs site as an example project built with BlazorStyled - let me know!

PSS - a new version is coming your way in a few days!

VR-Architect commented 4 years ago

Thanks for checking. Once we get the application up and running I will definitely send you the URL.

chanan commented 4 years ago

Hi @VR-Architect

I got it working. Had to add <text></text> to tell the compiler that the line inside the block is to be considered html: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#explicit-delimited-transition

Here is the sample code (I changed it a bit so to make it easier to test, but its the same basically):

    <Styled>
        .nav-item:hover {
            @if (IsGradiant)
            {
                <text>background: linear-gradient(to bottom, @color2 0 %, @color1 100 %); </text>
            }
            else
            {
                <text>background-color: @color1;</text>
            }
        }
    </Styled>

@code {
    private bool IsGradiant { get; set; } = false;
    private string color1 = "red";
    private string color2 = "hotpink";
}

The output when IsGradiant is true: .nav-item:hover{background:linear-gradient(to bottom, hotpink 0 %, red 100 %);} and when false: .nav-item:hover{background-color:red;}

Hope that helps! :)