Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

templates

Status
Not open for further replies.

kzn

MIS
Jan 28, 2005
209
GB
I have a dilemma and would appreciate any of your opinions:

My question is this should I use the second option? or stick to the way the book has taught me. Having such a templating system surely would complicate things? Any comments appreciated thank you.

The way I have been learning php via text books has shown me to use the following method
<?php
Require_once(‘dataconnection.php’);
Includes(‘header.html’);

Content made of php

Includes(‘footer.html’);
?>

I have come across another example on the web, which is made of three pages + index page:
Template.php
<?php
# THIS FUNCTION SWAPS OUT THE {{{ }}} TAGS WITH YOUR CODE
function get_template($template_name, $contentArray) {
global $settings;

# GET THE TEMPLATE
$path = $settings["DOC_PATH"].'templates/'.$template_name.'.html';

if(file_exists($path)) {

$handle = fopen($path, "r");
$templateContent = @fread($handle, filesize($path));
fclose($handle);

} else {
echo "Error: unable to open the temlpate from ". $path;
exit; // if it cant find the template ... stop the script
}


# REPLACE ALL THE TAGS
// get the doc path and add it to the contentArray
$contentArray["DOC_PATH"] = $settings["DOC_PATH"];

if(is_array($contentArray)) {
foreach($contentArray as $key => $value) {
$templateContent = str_replace('{{{'.$key.'}}}', $value, $templateContent);
}
}
return $templateContent;
}
?>
Renderpage.php
<?php

function render_page($page) {
# print the page to screen

echo $page;
}

?>

Runner.php
<?php

# ERROR REPORTING
error_reporting (E_ERROR | E_PARSE | E_WARNING);

# DATABASE CONFIG
$hostname = "";
$username = "";
$password = "";
$type = "";
$databasename = "";

# SET UP THE DATABASE CONNECTION
# $database = mysql_connect($hostname, $username, $password);
# mysql_select_db($databasename) or die("Could not select the database");

# SET UP TO SEE IF WE ARE IN THE ROOT OR NOT AND SET THE DOCPATH
# WE CHECK AGAINST PREFS.PHP AS THE LOCATION OF THIS FILE SHOULD NEVER CHANGE
if(file_exists("lib/prefs.php")) {
$docPath = ""; // we are in the root
} else {
$docPath = "../"; // we are not in the root
}

# GET A LIST OF FILES IN THE LIB FOLDER AND LOAD THEM, WE USE THE DOCPATH SET ABOVE TO LOCATE THE FILES
if($handle = opendir($docPath."lib/")) {
while (false !== ($file = readdir($handle))) {
if($file != "." && $file != ".." && eregi('.php$',$file)) {
$file = trim($file);
require_once($docPath . "lib/" . $file);
}
}
closedir($handle);
}

unset($handle);



# PUT GENERAL SETTINGS INTO THE SETTINGS ARRAY
$settings['DOC_PATH'] = $docPath;

# some examples like set the table names to be queried
# settings['users_table'] = "x_users"


?>

Index.php
<?

# START SESSION
session_start();


# REQUIRE FILES
require_once("lib/prefs.php");

# SET GLOBALS
global $settings;

# HEADER


# BODY
switch($_REQUEST["view"]) {

##########################################################################################################
# DISPLAY STANDARD PAGE
##########################################################################################################

case "":
default:

# PAGE NUMBER
//$page = 1;

# HOME WELCOME
//$repTags1["EDITION_DATE"] = edition_date();
$repTags["HOMEWELCOME"] = get_template("home_welcome", &$repTags1);
unset($repTags1);

# WELCOME BANNER
//$repTags1["ARCHIVESNAV"] = archives($page);
$repTags["WELCOMEBANNER"] = get_template("home_welcome_banner", &$repTags1);


# MAIN CONTENT
//$repTags1["TITLE"] = content_title($page);
//$repTags1["STORY"] = content_story($page);
//$repTags["CONTENT"] = get_template("content_home", &$repTags1);
unset($repTags1);


# FOOTER
//$repTags1["COLOR"] = navColor($page);
$repTags["FOOTER"] = get_template("footer", &$repTags1);
unset($repTags1);

# FULL WEBPAGE
$path = $settings["DOC_PATH"];
$body = get_template("_standard_page", &$repTags);
unset($repTags);



break;

}

$page = $body;
render_page($page, &$textArray);


?>

 
the answer is ... whatever floats your boat. i.e. whatever you find easier to work with.

but this changes with scale. for example, if you are developing in a multi-coder environment with some people on design/UI and others on functionality then, to avoid bottlenecks and ensure that the right people work on the right bits, templating is pretty much a requirement. how you do the templating is, again, a matter of team-preference. using functions is not my preference due to issues of variable scope.

recently I have changed to using a templating system that works something like the following

Code:
<?php require_once 'includes/bootstrap.php'; ?>
DOCTYPE
HEAD
SCRIPTS
STYLES
<?php despatch::despatch(); ?>
FOOT

bootstrap.php pulls in the database connection, global variables (with post overriding get). it also sets up (importantly) definitions and variables for directories so that they can be easily (absolutely) referenced from any script.

then in a script (typically an object) I would do something like this

Code:
require 'templates/form.html';

Code:
<form action="<?php echo FORMURL; ?>" method="post" >
<input type="text" name="something" value="<?php echo $this->something;?>" />
</form>

this has the advantage of providing (nearly) automated sticky forms as well as being a neat, low resource, method of templating. when you need to output a list or a table, you should put the template for that line item in a template file. you then have the choice of doing repeated include() or grabbing the content of the template into a variable and sequentially eval()'ing it.

Code:
$template = file_get_contents('templates/myListTemplate.html');
while ($row = mysql_fetch_assoc($result)){
  eval("echo $template;");
}
 
Have a read up around MVC (Model View Controller) which is often used in larger sites
 
@ingresman
have you used zend framework? i find their overly-anal implementation of MVC design patterns makes their application really opaque and difficult to work with.

however, i'm all for the logical separation that the mvc design pattern mandates. just not slavishly so. i see nothing wrong, for example, in including some form html within an object method, nor in including some procedural code (loops typically) within an html template.

 
No, not used the zend framework. I recall someone telling me (or it might have been here) that it requires 17 includes before any thing happens !
The ASP.NET MVC implementation is really nice. It has a new routing engine which lets you have search engine friendly urls, not used it in anger just had a play about and watched videos on it.
I wouldn't put HTML in a method unless that method was only doing presentation rendering. I very much into a business object (my term) doing just business rules and the rendering happening elsewhere. Classic example is so you can change the front end (even if it's only a new version of the browser for example or the introduction of a new front end such as mobile or even speech).
As for code in the template itself, yes I'm ok with this as long as it is only to do with presentation rendering e.g. alternate colours in a table.
 
I'm a self-taught PHP code. I've pulled my style from my programming experience(20 years) and reading several sites.

The last few sites I've done have a "shell.php" file that I give to whoever is doing the graphics and let them make a pretty empty page with headers, footers and what ever layout they need. The shell will have a function where ever dynamic content should go. The shell is included into my index and the index has the functions to support the calls from the shell.

The index does all the real work. creating the application object, setting up sessions, data connections, and managing user logins if required.
 
that sounds close to MVC too.

I suspect that, for web apps at least, all programmers end up tending towards an MVC design pattern if for no other reason than it makes picking up the code to maintain it at a later date a little bit less painful.
 
I know I shoudn't do this but.....
ASP/NET has a concept of master pages where you design you site look and feel and you can then have a content areas which is where the individual page logic goes. E.g. the master page may have things like naivgation, site map etc and the content areas have a list of products etc. However each page is stil seperate, the inherit from the master page. So if you change the look and feel of the master page the entire site gets that look and feel, bit like CSS on streriods.
The reason I mention this is looking at alan93rttt's post - are you saying that your site has only one page and it does everything the site needs sependant on context, input parameters etc ?
 
are you saying that your site has only one page and it does everything the site needs sependant on context, input parameters etc ?

that is how I design in php too. SEO is seldom relevant on my apps. when it is, I use mod-rewrite.
 
I can see mod-rewrite to show a nice URL to the user , but having all the code in one file does strike me as strange.
I could see the single file acting as a dispatcher and passing control onto the relevant .php.
But as you say at the top whatever floats your boat !
 
are you saying that your site has only one page and it does everything the site needs sependant on context, input parameters etc ?
No, but everything hubs off the index page. Based on parameters passed different pages are called each page has a common set of functions that the shell page will call to display the actual content.


Code:
mypage.php
<?php
displayPage(){

echo 'hello';

?>

Shell.php
<html stuff>
<?php displayPage();>
<more html>

Index.php
<?php
//db connection stuff
//session stuff
//app object stuff
//login/user stuff

if($pagevar=='test1') include('some page1.php');
else if($pagevar=='test2') include('some page2.php');
else if($pagevar=='test3') include('some page3.php');
else if($pagevar=='test4') include('some page4.php');
else if($pagevar='my') include('mypage.php');
else include('blank.php');
include('shell.php')


?>
Thats a real rough of the idea.







Alan
 
and for me, not everything is in one file!

index.php acts as a despatcher only.

 
Good , got you both now !
you guys worry me some time !!
I had a little play a while ago of creating a "masterpage" with a table i.e. r1 = banner
r2 in two columns, c1 being the navigation, c2 being my content area (included as a file)
R3 as a trailer (menu phone number etc)
Where the master page would be the only page a customer would see and the content area made the decision on what to show the user.
But I got distracted by Smarty and then christmas came along and suddently it's Feb !
 
i've never liked smarty. never got my head around it.
if you like it, what do you see as its key selling points?
 
i must admit it got bored reading the manual, it does look a bit complex for everyday use
 
I never liked smarty either. I downloaded it, looked at it, and saw that I would have to spend way too much time into grasping it, that it would need some serious object orientation instead of just a "God Class", and that I could write my own template system in less time than it would take to understand smarty. So I did.

It is called "TinyTemplate" and can be found at (it a subversion repository, but you can view it with any browser)

To see the structure, it is good to see the UML scheme at
It has got some extensions (database storage, control generation, table builders), but the above file basically is the system. Feel free to browse for the extensions and the sample project "StoryBoard".


+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
That looked interesting, however the certificate has a problem and I can't get to it (with i.e. 7 at least)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top