Extending Dwoo


Dwoo can be extended in many ways; you can add extra blocks, functions and filters*. You can even extend the Core itself for your application.

Globals

A global variable is like any other template variable, except that it’s available in all templates.

Actually globals are defined in the Core class and cannot be modified directly.
Since Dwoo 1.3.2, this feature is now available, let's see how to use it:
index.php
<?php
// create Core object
$core = new Dwoo\Core();
// assing new global variable named 'text'
$core->addGlobal('text', 'value');

You can now use your new global variable such as:

index.tpl
{$.text}

Extending Core

MyTemplate.php
<?php
class MyTemplate extends Dwoo\Core {

}

Creating custom Plugin(s)

In addition to providing you with an abundance of built-in plugins, Dwoo also allows you to create your own. These plugins may be implemented as user-defined functions or standalone classes, and can be either manually added at run-time via Dwoo’s addPlugin() method or automatically loaded by the Dwoo autoloader.

To illustrate, consider the following script, which sets up a simple plugin to manipulate email addresses:

index.php
<?php
// create Core object
$core = new Dwoo\Core();

// read template file
$tpl = new Dwoo\Template\File('tmpl/plugin.tpl');

// add custom plugin
$core->addPlugin('email_safe', function (Dwoo\Core $core, $str) {
   return str_replace(
     array('@', '.', '-'), 
     array(' at ', ' dot ', ' dash '), 
     $str
   );
});

// set sample string
$data['string']= 'vikram@example.com';

// interpolate values into template
// send interpolated result to output device
echo $core->get($tpl, $data);

Here, the fix_address() function replaces common email address characters with human-readable words, in order to make it harder for spammers to harvest these addresses from Web pages. The addPlugin() method takes care of adding this function to Dwoo’s plugin list, specifying both the local plugin name and the function callback.

Here’s how you’d use it in a template:

index.tpl
{email_safe($string)}

If you want add more than one custom plugin, you can specify to the loader a custom directory to search for, such as:

index.php
<?php
$core->getLoader()->addDirectory(__DIR__ . 'Views/plugins/');

Looking for help?

Couldn’t find what your are looking for ? Why not join our support chat and let us help you.

Discuss on Gitter

Table of contents