Search code examples
razorblazorblazor-server-side

Conditional div with blazor server


Here is what I want to do:

@if (condition)
{
  <div class="test">
}
<span class="test2">...</span>
@if (condition)
{
  </div>
}

This does not work because the Blazor compiler thinks the div is never closed.

So I need to do this:

@if (condition)
{
  <div class="test">
        <span class="test2">...</span>
  </div>
}
else
{
   <span class="test2">...</span>
}

It works fine, but I have a big code redundancy with the span.

How can I do this properly?

Please note div and span are examples. In reality, my code is bigger.

Thanks


Solution

  • What you're seeing is really a Razor syntax issue rather than specifically a Blazor issue. This question and answer cover it well.

    So, you can do what you're trying to do in the first example, but there are also other ways of solving that issue, at least one of which is Blazor specific (there are more no doubt):

    Make the class conditional

    Rather than trying to not render the div, you could make the class itself conditional.

    So in the code section of your page you could declare a property:

    @code {
    
        string myClass = "";
    
        protected override void OnInitialized()
        {
            if (condition) 
            {
                myClass = "whatever";
            }
        }
    
    }
    
    

    And then use that in your razor:

    <div class='@myClass'> 
        <span class="test2">...</span>
    </div>
    

    That way the span is only on the page once.

    Split the common code into a separate component

    Another approach is to make the common part (the span in this case) into a separate component and then render that component conditionally:

    @if (condition)
    {
        <div class="test">
            <YourComponent />
        </div>
    }
    else
    {
        <YourComponent />
    }
    

    That's probably overkill for the span in your example, but makes more sense where the new component would be replacing multiple lines of code.