PapT
PapT

Reputation: 623

How can I rewrite this blade if statement using a ternary operator?

How can I rewrite this if statement using a ternary operator?

@if($headerStyle->header_bg_color == NULL)

@else

style="background-color: {{ $headerStyle->header_bg_color }};"

@endif

thanks

Upvotes: 0

Views: 318

Answers (2)

Anuj Shrestha
Anuj Shrestha

Reputation: 1004

Using Ternary operator:

style={{$headerStyle->header_bg_color? 'background-color: '.$headerStyle->header_bg_color: null}}

PHP evaluates null, false, 0, and '' as false using them on a conditional statement.

So you don't need to strict check if the $headerStyle->header_bg_color is null or not.

If you don't want the style tag to be showing at all then

{!! $headerStyle->header_bg_color? 'style:"background-color: "'.$headerStyle->header_bg_color:'' !!}

You need to use {!! !!} to prevent blade escaping " " quotation marks

Upvotes: 1

knubbe
knubbe

Reputation: 1182

You don't need ternary for that. You can try something like this: @if($headerStyle->header_bg_color !== NULL) style="background-color: {{ $headerStyle->header_bg_color }};"@endif

Upvotes: 1

Related Questions