Home > php > PHP: faking templates

PHP: faking templates

In PHP, how to use templates without a template engine?

Well, the nice way would be to use a template engine, like Twig for instance.

But let’s say you don’t want to use a template engine (for some reason), but you still want to avoid spaghetti code where the controller and view parts are mixed up…

I have an idea for this. Maybe it’s a stupid thing, but I’d share it here. So, without a template engine you can still separate the controller and the view. However, this separation will be in the same PHP file :) On the top you’ll have the controller, where you collect the necessary data, and right below it you will have the view, where you simply use the variables defined in the controller. Let’s see two examples:

Way #1:

$c = array(
    'name' => 'PHP',
<!DOCTYPE html>
Hello <?= $c['name'] ?>!

Here, similarly to Twig, all data are collected in a hash. Now I call the hash simply “c” instead of “context“.

Way #2:
If you don’t want to use a hash, use simple variables. To make the variables that you want to use in the view part more visible, start their names with an underscore.

$_name = 'PHP';
<!DOCTYPE html>
Hello <?= $_name ?>!

What is gained? The controller and the view are not mixed. Although they are still in the same file, they are separated (top and bottom part of the source).

It can be an easy way to avoid spaghetti code. However, as mentioned before, the ideal solution would be to use a real template engine.

We could call it the poor man’s templating system :)

Categories: php Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: