Oleh: kod34fr33 | 3/Juli/2007

CakePHP lightweight template helper

I dont like template engine that:

  • you could use php code on the template
  • use neo/strange tag/language

so i made this helper. as the name, this is lightweight template engine, so this helper only do a templating. :) and the template file content only html. really.

well, i still have problem with snippet, so you could download the code here (dont forget to change file extension with .php and save it on app/views/helpers folder).

for sample of usage, i would show you how to build multiply table (no database used of course :p ).

url used : /test/multiply

controller content: filepath : app/controller/test_controller.php ( ups.. i’m forget to declare helpers :p )

class TestController extends AppController {
   var $name = "Test";
   var $uses = array(); //no db used. remember?
   var $helpers = array("template","html"); //updated 06/07/2007
   function multiply() {
   }
}
?>

before we continue to view and template file, first, we must set configure the template helper in order to to work properly. below are configuration needed:
a. template folder : this is similar to app/view folder; the path where all template file is under.
b. file extension : template file extension (like thtml for view)
c. block splitter sign : pattern to split template into blocks.
d. block name : pattern to determine block name (preg_match compat)

well, now i used the default configuration:
a. template folder : /app/templates
b. file extension : tmpl
c. block splitter sign : <!–blockSplitter–>
d. block name : <!–name=(.*)–>

if you want change this configuration, change it on templatehelper class.

OK, now let’s start build view and template file.

view content : filepath : /app/views/test/multiply.thtml

$template->startup($this->controller->viewPath,$this->controller->action);
$template->add("header"); //add header block to output$template->add("tableOpen"); //add tableOpen block to output
$b = 3;
for($a=1;$a<11;$a++) {
  $c = $a * $b;
  $template->add("tableRow",array("a"=>$a,"b"=>$b,"c"=>$c);
}
$template->add("tableClose");
$template->display();
?>

and finally, the template file…

template content : (file path: /app/templates/test/multiply.tmpl)

<!--blockSplitter-->
<!--name=header-->
<div align="center">Multiplier table with template</div>
<!--blockSplitter-->
<!--name=tableOpen-->
<table>
<!--blockSplitter-->
<!--name=tableRow-->
<tr>
<td>__a__ x __b__</td>
<td>__c__</td>
</tr>
<!--blockSplitter-->
<!--name=tableClose-->
</table>

Thats all folk. any question?

Update
recently i found template engine that work similar: Pattemplate.
i haven’t try this, but it looks promises.


Beri tanggapan

Your response:

Kategori