Creating a custom PHP template -
i created custom php templating system , way built seems, well, inefficient. 3 main goals template to:
- pull site-wide html elements template.tpl include.
- be able dynamically assign content in template.tpl (like
<title>or<script>) - be efficient , scalable possible.
in end, template system looked this:
randompage.php
<?php // declare page specific resources $pagetitle = "random sub-title"; $pageresources = "/css/somerandomcss.css" $pagecontent = "/randompage.tpl" // include generic page template include dirname($_server['document_root']).'/includes/template.tpl' ?> randompage.tpl
<h1><?=$pagetitle?></h1> <p>some random page's content</p> template.tpl
<!doctype html> <html lang="en"> <head> <title>my site -- <?=$pagetitle?></title> <link href="/css/styles.css" rel="stylesheet" type="text/css"> <link href="<?=pageresources?>" rel="stylesheet" type="text/css"> </head> <body> <? include $pagecontent ?> </body> </html> the main problem system every web page, need manage two files: 1 logic/data , other page template. seems largely inefficient me, , doesn't seem scalable approach.
recently, come across smarty framework, allow me consolidate system randompage.php , randompage.tpl like:
randomsmartypage.php
{extends file="template.tpl"} {block name=pagetitle}my page title{/block} {block name=pageresources} <link href="/css/somerandomcss.css" rel="stylesheet" text="text/css"> {/block} {block name=pagecontent}my html page body goes here{/block} seeing approach raised 3 major questions me:
- are there fundamental flaws how approaching templating system?
- can original php code refactored don't have create 2 files every web page?
- would using smarty (or perhaps alternative framework) idea in case?
- your code isn't using templating engine besides php itself, fine. flaw can see template have access variables, , ones create global.
- two files system, 1 change preprocessed , passed view, , 1 view itself, containing html or whatever. allows swap views, example, view standard browsing , mobile view mobile browsers.
- it can idea, i'm firm believer using php enough.
here example, untested. encapsulate variables don't pollute global namespace.
index.php
function view($file, $vars) { ob_start(); extract($vars); include dirname(__file__) . '/views/' . $file . '.php'; $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } echo view('home', array('content' => home::getcontent())); views/home.php
<h1>home</h1> <?php echo $content; ?>
Comments
Post a Comment