How To

Learn how to create templates in BitFrame Microframework

Create Templates

Choosing A Templating Engine

To create templates you can easily do any of the following:

  1. Incorporate any PHP templating engine available on the internet;
  2. Create a custom templating system;
  3. Use the \BitFrame\Renderer\PlatesRenderer add-on.

BitFrame core comes bundled with the following two classes (adopted from Zend Expressive) that may aid in developing your custom templating system:

  1. \BitFrame\Renderer\TemplateInterface: interface defining required template capabilities.
  2. \BitFrame\Renderer\TemplatePath: an object store for storing namespaced path in which templates reside.

For an example you could see the \BitFrame\Renderer\PlatesRenderer add-on which uses these classes.

Using A Template Engine

Let's assume that you've initialized your templating engine into a variable, for example $tpl. In order to use it, see the various possibilities below:

Inside A Class:

If you wish to use your template object inside a class, simply typehint it. For example, if it's using (the recommended) \BitFrame\Renderer\TemplateInterface, then you may inject the template handler like so:

use \BitFrame\Renderer\TemplateInterface;

class SomeClass
{
    private $tpl;

    public __construct(TemplateInterface $tpl) 
    {
        $this->tpl = $tpl;
    }
}

// pass $tpl (template handler) into class
$obj = new SomeClass($tpl);

Now you could access your template handler throughout your class.

Inside An Anonymous Class:

PHP 7+ allows us to create anonymous classes. We can pass arguments through to the constructor of an anonymous class like so:

use \BitFrame\Renderer\TemplateInterface;

// pass $tpl (template handler) into class
$obj = new class($tpl)
{
    private $tpl;

    public __construct(TemplateInterface $tpl) 
    {
        $this->tpl = $tpl;
    }
}
Inside Functions:

In PHP anonymous functions/closures (where for some reason we may be unable to pass our template object as an argument) we would need to explicitly grant permission to the function to access variables that are outside of the context of the function. We can do this by using the use keyword like so:

use \BitFrame\Renderer\TemplateInterface;

// pass $tpl (template handler) into function
$x = function() use ($tpl) {
    // do something
}

Similarly, for a named function you could use the global keyword to allow the function to access variables that are outside the context/scope of the function.

Comments

Let us know if you have something to say or add