Using PHP as a Template Engine

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.

How to use php as a template engine without requiring third party libs

PHP can itself be used as a template engine in a pinch. Write templates in individual files like:

Hello, <?= htmlspecialchars($name) ?>!

They can be rendered with a simple function like:

function render_template($_path, $_vars=array()) {
extract($_vars, EXTR_SKIP);
ob_start();
require($_path);
return ob_get_clean();
}

In practice:

print render_template("templates/hello.php", array("name" => "world"));

-> Hello, world!

The ob_start() and ob_get_clean() in render_template() may be omitted if you always want to render templates directly. (That is, if you will always want the output of a template to be printed, rather than returned as a string.)

Note that the use of underscores in the variable names $_path and $_vars is significant: it reduces the risk that they will conflict with variables used by the template itself.

How to make a php template engine?

What if, for a script easier to maintain, you move those to functions?

something like this:

<?php

function get_content($file, $data)
{
$template = file_get_contents($file);

foreach($data as $key => $value)
{
$template = str_replace('{'.$key.'}', $value, $template);
}

return $template;
}

And you can use it this way:

<?php

$file = '/path/to/your/file.php';
$data = = array('var1' => 'value',
'txt' => 'text');

echo get_content($file, $data);

Why should I use templating system in PHP?

Yes, as you said, if you don't force yourself to use a templating engine inside PHP ( the templating engine ) it becomes easy to slip and stop separating concerns.

However, the same people who have problems separating concerns end up generating HTML and feeding it to smarty, or executing PHP code in Smarty, so Smarty's hardly solving your concern separation problem.

See also:

  • PHP as a template language or some other templating script
  • What is the best way to insert HTML via PHP


Related Topics



Leave a reply



Submit