Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP as a template engine

Tags:

php

templates

I am not going to argue about the choice of a template engine against only PHP. I choose not to use a template engine, like Smarty, because I would like to learn how to properly design a template using PHP and HTML. Could someone provide links or examples on how to design a template page?

like image 214
Shoe Avatar asked Feb 12 '11 10:02

Shoe


People also ask

Is PHP a template engine?

PHP is not a template engine, but a language that can be used to write templates, or template engines. A template engine is not just a language, but also the programming API that allows the scripts to locate, organize templates or assign the data from the script to them.

Can you put PHP in a Twig file?

Symfony defaults to Twig for its template engine, but you can still use plain PHP code if you want.

What is the best templating engine?

Mustache. Mustache is one of the most widely known templating systems that works for a number of programming languages, including JavaScript, Node. js, PHP, and many others. Because Mustache is a logic-less templating engine, it can be literally used for any kind of development work.

What is the purpose of templates in PHP explain two advantages of templates?

A PHP template engine allows developers and designers to work on the same areas, but without disturbing each other. The data fetched and proceeded by backend will be delivered to a template where they can be modified and displayed as final output.


2 Answers

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.

like image 178
Richard Knop Avatar answered Sep 18 '22 20:09

Richard Knop


It's really not all that difficult.

Non-PHP goes out here
<?php # PHP goes in here ?>
More non-PHP goes out here
<?php # More PHP goes in here ?>
like image 37
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 20:09

Ignacio Vazquez-Abrams