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?
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>
Different frameworks have different accepted practices; in Django, for example, it's frowned on to put any logic in template files.
I've always preferred to keep the controller relatively clutter-free though - especially if it's something as simple as choosing between two images to display.
Ultimately, it's your choice, but for me, simple conditionals and loops are fine in templates.
精彩评论