Using Template on PHP

Using Template on PHP

This separates the page into two PHP files: (1) the first obtains the data, and (2) the second displays the data.

While getting data, not a single character should be printed out.

If some errors occurred, display an error page.

Once you get all your data with no errors - it's time to include a template. The template has two PHP files as well: the template for the page itself and the template that is shared in common by all the pages in the site.

By sorting things this way you'll solve all your present and future templating problems.

A typical script may look like

<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.php";
include "template.php";
?>

where template.php is your main site template, including common parts, like header, footer, menu etc:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>

and links.php is the actual page template:

<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><a href="<?=$row['link']?>" target="_blank"><?=$row['name']?></a></li>
<? endforeach ?>
<ul>

easy, clean and maintainable.

settings.php contains all common settings:

<?php
$hostname_conn,$database_conn,$username_conn,$password_conn,$conn;
$hostname_conn = "localhost";
$database_conn = "test";
$username_conn = "****";
$password_conn = "****";
$conn = mysql_connect($hostname_conn, $username_conn, $password_conn)
or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("SET NAMES 'utf8'") or trigger_error(mysql_error(),E_USER_ERROR);

$tpl = "default.php";
$pagetitle = "";

function dbgetarr(){
$a = array();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);

$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}

?>

HTML Templates -- php?

Using php includes:

Save this as top.php

<html>
<head>
<title><?php echo $title; ?></title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />

</head>
<body>
<div id="container">
<header>
<img src="images/banner.png" alt="World War I" style="border: none"/>
<nav>
<ul>
<a href="index.htm"><li><span>Home</span></li></a>
<a href="1914.htm"><li><span>1914</span></li></a>
<a href="1915.htm"><li><span>1915</span></li></a>
<a href="1916.htm"><li><span>1916</span></li></a>
<a href="1917.htm"><li><span>1917</span></li></a>
<a href="1918.htm"><li><span>1918</span></li></a>
</ul>
</nav>
</header>
<section>

Save this as bottom.php

<aside>
</aside>
</section>
<footer style="font-weight: bold; letter-spacing: .1em">
<a href="citations.htm">Citations</a> •
<a href="about.htm">About</a>
</footer>
</div>
</body>
</html>

Then your individual pages would be like this:

<?php $title = '1914'; include("top.php");?>
//This would be where you would make the changes that need to be made on each page.

<article>
<br style="clear: both" />
</article>

<?php include("bottom.php");?>

Including template file in PHP and replacing variables

One way you could do it:

$replace = array('{page_title}', '{site_name}');
$with = array('Title', 'My Website');

$contents = file_get_contents('my_template.tpl');

echo str_replace($replace, $with, $contents);

Update: removed include, used file_get_contents()

How to insert template in php file

As @ianhales mentioned, you can use str_replace() for replacing white-spaces in the name. If I understand your question correctly, you want to use a template file to generate the contents of the PHP file. To do that, I would do the following.

Create template.txt file

<?php
$var = #THEVAR#;
?>

Then you use the template:

<?php
...
$value = 5;
$template = file_get_contents('template.txt');
$template = str_replace("#THEVAR#", $value, $template);
$newFile = fopen($compname.'.php', 'w');
fwrite($newFile, $template);
fclose($newFile);
...

How to template in PHP... the right way?

I would personally say the first approach is best, because it keeps all documents and document fragments semantically complete.

The second approach means that you'll have a <div> in your header.tpl that is closed by a </div> in your footer.tpl (except likely there will be a few tags that applies to). This means if you change your layout, by adding a wrapper div (for example) somewhere, you have to remember to also close it in another file (or, depending on your layout, two or three different files).

It's worse with several different embedded files. Think of how hard it is to debug a site, when one file - that gets included conditionally - has an extra </div>. You get a vague bug report "sometimes the page looks completely messed up, doesn't matter what browser I use" that is very very hard to track down. It's MUCH worse if you're using table-based layouts..

Using the first approach, you can still use the DRY principle. You load the template into a variable. eg:

$userVars['name'] = $currentUser->name;
$templateVars['userinfo'] = $template->load('userinfo.php', $userVars);

...
$template->display('template.tpl', $templateVars);

You can continually nest documents that way. There are many benefits:

  • Each file is semantically complete HTML - all tags that are opened, are also closed in the same document. It's easy to edit one part of the layout without breaking (possibly unknowningly) anything else.
  • It's each to cache the output of certain templates, and re-use them
  • It's easy to apply AJAX to the site. For example, you have a stats.tpl template rendering inside a <div id="stats"> on the first page load. You also have a view that just renders the stats.tpl template by itself, and then use jquery to do $('#stats').load('/ajaxstats.php'), which refreshes that div but without repeating code at all.

Creating html templates using PHP

One word: Organization. Separating each part of the page will allow each of them to be viewed/edited separately. This simple concept is very beneficial. For example, anyone in the team that want to handle login process can easily figure out that they have to edit login_form.phtml and they can be sure that editing login_form.phtml will less likely to unintentionally interfere with other functionalities.

As of the best practice, here is how I do it (not exactly but similar).

$Title = 'Blah Blah Blah';
$User = 'Jon Miller';

$ThemeName = "MyGreenPage";
$Contents = array("User", "Login_Form");

function Include($FileName) {
if (file_exists($FileName))
include $FileName;
}

MyGreenPage.phtml:

<html>
<head>
<title><?php echo $title; ?></title>
<?php
foreach($Contents as $Content)
Include("$Content.pcss");
?>
<?php
foreach($Contents as $Content)
Include("$Content.pjs");
?>
</head>
<body>
<?php
foreach($Contents as $Content)
Include("$Content.phtml");
?>
</body>
</html>

User.pcss:

/*  Some styles needed by User */

User.pjs:

/*  Some script needed by User */

User.phtml:

    <h3><?php echo $user; ?></h3>

Login_Form.pcss:

/*  Some styles needed by Login_Form */    

Login_Form.pjs:

/*  Some script needed by Login_Form */

Login_Form.phtml:

    <form>login form</form>

Let me remind you again that this is not that exactly what I do (what I do use OOP) so this may not exactly run as is and you may need to edit it.



Related Topics



Leave a reply



Submit