Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

how to write conditional statements inside div html?

Writer Matthew Barrera

I have a requirement of showing 2 div's based on a condition like if value is '1' show one div else if value is '0' display another div. Below is my code:

<div <?php if($campaign[0]->method != 'CSV'){ echo "style='display:none'"; } ?> > ----------- ------------
</div>
<div <?php if($campaign[0]->method != 'API'){ echo "style='display:none'"; } ?> > ---------- ----------
</div>

Code is looking fine but not working properly. I am trying to achieve this in Laravel 5.4 framework. Any help would be appreciated. Thanks

4

4 Answers

you can do inline if statements like this:

<div <?php echo ($campaign[0]->method != 'CSV' ? 'style="display: none;" : ''); ?>></div>
() - starts the if statement and closes
? - is the if condition is met
: - is the else
9

It is easy to drop into and out of the PHP processor which will allow you to put the logic into the html file. The following also uses PHP Alternative syntax for control structures

I removed the style="display: none"; bits as I assume that was included to hide the alternate <div>.

<?php //drop into PHP processor mode
if($campaign[0]->method != 'CSV'): //now, back to html processing mode ?> <div> <!-- html markup--> </div>
<?php elseif($campaign[0]->method != 'API'): ?> <div> <!-- html markup--> </div>
<?php endif; ?>

This is not an exact response to your answer, but you need to have in mind that doing display: none you can always show it playing with the css a bit. In order to prevent that, you should use conditional in php to only render what you desire to show, to prevent the code to be visible. I'd do this way:

<?php if($campaign[0] == 'CSV'):?> <div> ----------- ------------ </div>
<?php elseif($campaign[0] == 'API'):?> <div> ---------- ---------- </div>
<?endif;

Or using a switch if there are more options than CSV and API

Use short form of if statement, and write it inside of curly braces as laravel blades' echo.

<div {{ $campaign[0]->method != 'API' ? "style='display:none'" : "" }}>

It may help you

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy