Using PHP as a template engine

Just use alternative PHP syntax for if/for/foreach control language constructs which are designed specifically for this purpose:

    <h1>Users</h1>
<?php if(count($users) > 0): ?>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
<?php foreach($users as $user): ?>
            <tr>
                <td><?php echo htmlentities($user->Id); ?></td>
                <td><?php echo htmlentities($user->FirstName); ?></td>
                <td><?php echo htmlentities($user->LastName); ?></td>
            </tr>
<?php endforeach; ?>
        </tbody>
    </table>
<?php else: ?>
    <p>No users in the database.</p>
<?php endif; ?>

I also suggest creating view helpers for HTML outputs that are very similar and use them instead of having repeated HTML code.

Leave a Comment

tech