0
votes

I have a list collection of umbraco pages and i want to loop through checking if a bool property is true and if so i want to apply a specific class to the div

How can i write an else if ternary operator in razor to apply a class to to a div. If i wasnt using ternary then it would look like this

if package.GetPropertyValue<bool>("test")
{
  <div class="test1"></div>
}
else if (package.GetPropertyValue<bool>("test1"))
{
  <div class="test1"></div>
}
else if (package.GetPropertyValue<bool>("test2"))
{
  <div class="test2"></div>
}

in my razor view it would be something like as follows (but not right)

<div class="@(package.GetPropertyValue<bool>("test") ? "test" : package.GetPropertyValue<bool>("test1") ? "test1" : "test2" )"></div>

Can this be done or can someone suggest how I can apply a specific class to that div when a specific condition is met?

many thanks paul

1

1 Answers

1
votes

Yes, you can nest ternary operators, but be careful going too nuts, or you can render the code quite hard to read. You could do something like:

@{
var css = package.GetPropertyValue<bool>("test") ? "test" : 
    package.GetPropertyValue<bool>("test1") ? "test2" : 
      package.GetPropertyValue<bool>("test2") ? "test3" : "";
}
<div class="@css"></div>

However, this seems like a bad bit of design. What if they want another class later on? You'd have too add another level of nesting to the ternary operator, and again the next time etc. If this property is just for setting the style, why not have a single property with a dropdown that lets them choose the style instead, eliminating the need for the nested ternary operators.