seoppc
seoppc

Reputation: 2824

How to use custom PHP templated system

We are building an app and would like to separate html part from code(php) part, how can we use following template file with php?

<h1>{$heading}</h1>
<p>{$content}</>

And php code as following...

<?php
$heading = $row['heading'];
$description = $row['content'];
?>

how can we inlclude tpl file and use it? thanks.

Upvotes: 0

Views: 266

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157876

In fact, that's unusable templating system.

Imagine there will be 20 headings and 20 descriptions on the page? Gonna write them all? And then HTML got changed and you'll have to change it 20 times? There is no benefit in such template.

In fact, there is not a single reason in separating HTML from PHP.

It's business logic should be separated from presentation logic, as you'll have to use some logic in your template anyway. And PHP is as good for this as any other templating language.

Just separate your code into 2 parts: getting data part and displaying part.

Make your regular PHP page get all required data, then define a template for this data and then call main site template, which will render whole page.

Well, here is a rough example of such separation.
Imagine you have links.php page contains links to friendly sites. this page should get all required data and then call a template:

<?
//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.tpl.php";
include "main.tpl.php";
?>

where main.tpl.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.tpl.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>

Upvotes: 6

JohnP
JohnP

Reputation: 50039

You shouldn't rewrite proven and existing functionality unless you have a very good reason. That markup is very similar to Smarty. Have a look at this : http://www.smarty.net/

If you want to rewrite it, then you might want to look at output buffering. Or you could create your own view framework where you set variables to a view object and it does all the code/scope management for you ala Zend, CakePHP

Upvotes: 0

Related Questions