Blazor Razor return statement in HTML

Viewed 562

I recently inherited a Blazor project and come across many .razor files that are like:

<h1>Some header text></h1>
@if(someCondition) {
<div> lots of html and what not here taking up many lines</div>
} else {
<div> more html taking up many lines</div>
}

What I'm wondering is if there is a syntax that will allow me to eliminate the "else" statements that are hiding in the weeds, by having a return statement in my "if" condition. Meaning:

<h1>Some header text></h1>
@if(someCondition) {
<div> lots of html and what not here taking up many lines</div>
return //JUST BAIL HERE INSTEAD OF HAVING TO START AN ELSE BLOCK LIKE I DO ELSEWHERE IN LIFE
}

<div> more html taking up many lines</div>
2 Answers

Yes. You can use return; this ends the RenderFragment no other content is drawn.

blazor repl

Yes, you can, as Brian's answer shows, but Razor encourages breaking your markup into components that can be composed easier. In this case, I would consider breaking out your <div></div> elements into their own components, making the resulting Razor simpler:

<h1>Some header text></h1>
@if(someCondition)
{
    <component1 />
}
else
{
    <component2 />
}

Edited to add:

Imagine trying to figure out why some giant chunk of markup is not rendering in some page, what with no conditionals surrounding it. Only to find that there's some unexpected return statement in the middle of the the component. I don't think I would react nicely if that were me.

Related