Wednesday, September 10, 2008

Combining PHP and HTML pages

A while ago, one of my clients gave me the source code for one of his websites for me to make some adjustments. The first thing that shocked me when I was going through this code, was the fact that all of the HTML code was inside the PHP pages.

This is just awful. It’s almost like having a toilet inside of your office (although many of you would like that). PHP pages must only contain the logic of your website and HTML pages must be used for the GUI (Graphical user interface).

There is an easy way to combine PHP and HTML into a single output: Smarty (http://www.smarty.net). Smarty is a template engine which allows you to parse a HTML page from a PHP page. You don’t need to install anything. Just download the PHP code and include it on your project.

Here’s a quick example:

index.php
 
<?php

// Smarty initialization
require_once('Smarty.class.php');
$smarty = new Smarty();

$smarty->display(‘index.html’);

?>

index.html

<html>
<head>
<title>Smarty test</title>
</head>
<body>
This is a test!
</body>
</html>

Of course, there are many other many advanced uses for this tool which you can read about from the Smarty Manual. Here are some examples:

Example 1: Variables

Let’s say you want the title of your page to be a variable which you can change from a PHP script. This is the way to do it using Smarty:

index.php

<?php

// Smarty initialization
require_once('Smarty.class.php');
$smarty = new Smarty();

$smarty->assign(“title”, “My title”);
$smarty->display(‘index.html’);

?>

index.html

<html>
<head>
<title>{title}</title>
</head>
<body>
This is a test!
</body>
</html>

You can also assign arrays or objects and use them on you HTML page as well.

Example 2: Loop sentences

Imagine you want to display a list of all your friends, which are stored in an array. This is how you could do that with Smarty:

index.php

<?php

// Smarty initialization
require_once('Smarty.class.php');
$smarty = new Smarty();

$myFriends = array(“Mike”, “Paul”, “Peter”, “John”);
$smarty->assign(“myFriends”, $myFriends);
$smarty->display(‘index.html’);

?>
index.html

<html>
<head>
<title>My Friends</title>
</head>
<body>
My friends are:
<ul>
{foreach from=$myFriends item=friend}
<li>{$friend}</li>
{/foreach}
</ul>
</body>
</html>
I hope this brief tutorial was useful for you. If you have any questions, please leave a comment and I’ll try to reply as soon as possible.

No comments: