Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it clean to have conditional statements within Codeigniter views?

I am currently trying to separate my Views as much as possible from my Controllers. Ideally I would like to have minimal PHP in my view, except variable names, etc. These variables are being passed in from the controller.

But is it clean to have IF statements (or the like) within a view?

For example

// Controller 

$data['status'] = 'pass';

$this->load->view("Status Page", $data);

And ..

<!-- View -->
<div>
    <?php if($status === 'pass') { ?>
    <img src='passIcon.jpg'>Pass
    <?php } else { ?>
    <img src='failIcon.jpg'>Fail
    <?php } ?>
</div>

The closest thing I found to an answer on SO was Conditionals in Views

This was for ASP, and I guess the principles still apply. I could bring the conditional statements back into the controller, but then the controller would be creating HTML and sending it to the view, which isn't right either.

Is there any way to avoid this cross over? Or will there always be fragments of PHP in views?

like image 737
Chris Avatar asked Oct 18 '25 15:10

Chris


1 Answers

From my point of view, it's the view's job to render the data , so if you need conditions to display it proprely then by all means do it , as it will avoid duplicate html code to split it in 2 views and test the var in the controller .

Allso another good practice would be to use the alternative syntax in the view as it makes following gode much easyer . Eg :

<!-- View -->
<div>
    <?php if ( $status === 'pass' ) : ?>
        <img src='passIcon.jpg'>Pass
    <?php else : ?>
        <img src='failIcon.jpg'>Fail
    <?php endif; ?>
</div>

However taking you're example a bit further you can have the src set in the controller ( i must admit that there will be times where you'll need conditional in views ) :

Controller

$data['src'] = ( $data['status'] === 'pass' ) ? 'passIcon.jpg' : 'failIcon.jpg';
$data['text'] = ( $data['status'] === 'pass' ) ? 'Pass text' : 'Fail text';

$this->load->view("Status Page", $data);

View

<!-- View -->
<div>
    <img src='<?php echo $src; ?>'><?php echo $text; ?>
</div>
like image 111
Poelinca Dorin Avatar answered Oct 20 '25 05:10

Poelinca Dorin