Reputation: 2214
I want to separate my presentation layer from the logic layer but I'm unsure what I should do when I have to loop or check stuff within the presentation layer?
Variables and other somewhat static content is easy, I can either do
<div class='description'><?php echo $product['description']; ?></div>
or
<div class='description'>{{product_description}}</div>
But how about looping stuff?
Let's say I'm creating a list of users within a table. Is there any other way except putting up a foreach within the view and printing HTML inside the foreach?
<table>
if (!empty($users)) {
foreach ($users as $key => $value) {
echo "<tr data-user-id='$value[id]'>";
echo "<td>$value[id]</td>";
echo "<td>$value[first_name]</td>";
echo "<td>$value[last_name]</td>";
echo "<td><a href='?id=$value[id]&edit=1' class='edit'>Edit</a></td>";
echo "</tr>";
}
}
</table>
This would work perfectly fine but I can't get over the fact that it's not looking so "viewish" anymore. Is it possible to get the view cleaner? What about when I have to add conditions? It gets more and more messy.
Upvotes: 0
Views: 82
Reputation: 363
Sounds like the main problem your having has to do more with making the view presentation readable. An easy way to accomplish this using PHP templates is to use the alternative syntax for control flow structures. Doing this can make a template look much more readable, similar to twig for instance.
Using your example:
<table>
<?php if (!empty($users)): ?>
<?php foreach ($users as $key => $value): ?>
<tr data-user-id="<?php echo $value[id]; ?>">
<td><?php echo $value[id]; ?></td>
<td><?php echo $value[first_name]; ?></td>
<td><?php echo $value[last_name]; ?></td>
<td><a href="<?php echo "?id={$value[id]}&edit=1"; ?>" class="edit">Edit</a></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>
Notice that I've removed the open curly braquet {
and replaced it with a :
. This is then closed on line 10 with a endif;
. Same idea is repeated with foreach. This is the alternate syntax for control structures. Normally in business logic You would us the other form, but this can really help when you need to write readble template code for view presentation layers.
Upvotes: 1