HomePHP Page 2 - Template-Based Web Development With patTemplate (part 2)
Scoping It Down - PHP
Got the basics down? Well, here's the advanced course - thisarticle demonstrates some of patTemplate's more sophisticated features,including the ability to dynamically show or hide templates, inheritvariables, use loops and conditional branches, and create dynamic,template-based forms and error handlers.
You've already seen how to use the AddVar() method to replace template variables with actual values. However, template variables are "local" to a template, and so, the value assigned to a template variable cannot be accessed from other templates (actually, that's a little white lie which I'm going to recant on the next page, but bear with me for a moment).
In the event that you need a variable which is "global", and whose value can be accessed from more than one template, patTemplate offers the addGlobalVar() method call, which makes the value of a template variable available to all other templates.
Take a look at the following templates, all of which use the template variable {IMAGES}:
Now, rather than making three calls to AddVar() - one for
each of the templates referencing the variable {IMAGES} - I can save myself time with a single call to AddGlobalVar(), which makes the value of {IMAGES} available in the global namespace. Here's the script:
<?php
// include the class
include("include/patTemplate.php");
// initialize an object of the class
$template = new patTemplate();
// set template location
$template->setBasedir("templates");
// add templates to the template engine
$template->readTemplatesFromFile("app1.tmpl");
// add global variable
$template->AddGlobalVar("IMAGES", "/app1/images");
// parse and display the template
$template->displayParsedTemplate("main");
?>