Creating a custom PHP template -


i created custom php templating system , way built seems, well, inefficient. 3 main goals template to:

  1. pull site-wide html elements template.tpl include.
  2. be able dynamically assign content in template.tpl (like <title> or <script>)
  3. 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:

  1. are there fundamental flaws how approaching templating system?
  2. can original php code refactored don't have create 2 files every web page?
  3. would using smarty (or perhaps alternative framework) idea in case?

  1. your code isn't using templating engine besides php itself, fine. flaw can see template have access variables, , ones create global.
  2. 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.
  3. 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

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -