Snacks from the new PHPixie Template

    Another library from PHPixie has become available today , this time it is a template engine. As in the previous version, PHP itself is used as a language, but now new features have been added including a block approach to template inheritance. We will talk about this later, and now about the most delicious: compilation of arbitrary formats. PHPixie Template allows you to use almost any format, just provide a compiler that translates it into PHP, and file uploading, caching, etc. will be done for you. Also, this means that you can use multiple formats at the same time in one project.

    So let's try making friends with Template HAML. To do this, use the mthaml / mthaml package

        "require": {
            "phpixie/template": "3.*@dev",
            "phpixie/slice": "3.*@dev",
            "mthaml/mthaml": "1.7.0"

    Create the easiest wrapper:

    mtHaml = new \MtHaml\Environment('php');
        //Расширения файлов которые обрабатывает наш формат
        public function handledExtensions()
            return array('haml');
        //Сама компиляция
        public function compile($file)
            $contents = file_get_contents($file);
            return $this->mtHaml->compileString($contents, $file);

    It remains only to transfer our new format through the constructor to the Template itself:

    //Вспомогательная библиотека о которой я еще расскажу
    //Используется для представления данных, в данном случае конфига
    $slice = new \PHPixie\Slice();
    $config = $slice->arrayData(array(
        'resolver' => array(
            'locator' => array(
                //Папка с шаблонами
                'directory'        => __DIR__.'/templates/',
                'defaultExtension' => 'haml',
        'compiler' => array(
            //Где сохранять скомпилированные файлы
            'cacheDirectory' => > __DIR__.'/cache/',
    $template = new \PHPixie\Template($slice, $config, array(), array(
        new HamlCompiler()

    Now all haml templates will be automatically compiled and cached. Thus, you can invent or adapt any language, while preserving all the other features of the library, such as inheritance and extensions.

    In the previous version, the only way to connect one template to another was to include . That is, the page rendering had to go from top to bottom by connecting the necessary templates along the way. The disadvantage of this approach is that the connected template cannot change anything in the parent. Now let's see what is available to us now:

    //файл layout.php
            <?php $this->block('title'); ?>
            childContent(); ?>

    //файл fairy.php
    layout('layout'); ?>
    startBlock('title'); ?>
    Fairy page
    endBlock(); ?>


    The fairy.php template extends layout.php with the ability to override blocks in the parent template. Those who use Twig are very familiar with this approach. For those who prefer to use include, this is still possible:
    include $this->resolve('fairy');

    Searching for a template Template
    engines often have a template search mechanism, where if a template is needed it is not found, another one is used instead. Often this is necessary when creating new topics based on old ones. Instead of just one approach, the PHPixie Template allows you to customize your search using a combination of 3 locators:

    • Driectory - searches the directory by file name, the most standard
    • Group - groups locators, the search is conducted in each locator in turn
    • Prefix - Allows you to add a prefix to the name

    Take a look at this config:
        'resolver' => [
            'locator' => [
                'type'     => 'prefix',
                'locators' => [
                    'Site' => [
                        'directory'  => __DIR__.'/site/',
                    'Theme' => [
                        'type'       => 'group',
                        'locators'   => [
                                'directory' => __DIR__.'/templates/',
                                'directory' => __DIR__.'/fallback/',

    Thus, the Site :: layout template will be searched in the site / folder , and Theme :: home in the templates / and fallbacks / folders .

    Extensions are classes that add additional functions to templates. As an example, let's look at the HTML extension, which is used to output and escape strings.

    class HTML implements \PHPixie\Template\Extensions\Extension
        public function name()
            return 'html';
        //Методы из \того массива будут доступны в шаблонах
        public function methods()
            return array('escape', 'output');
        //Также для удобности можно некоторые функции назначит в переменные
        //в данном случае это позволит использовать $_($name) вместо $this->output($name)
        public function aliases()
            return array(
                '_' => 'output'
        //Сами методы
        public function escape($string)
            return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
        public function output($string)
            echo $this->escape($string);

    Such extensions, similar to formats, can be passed through the constructor.

    To try the DIY template yourself:
    git clone
    cd template/examples
    #если у вас еще нет Композера
    curl -sS | php
    php composer.phar install
    php quickstart.php

    And by the way, like all other libraries from PHPixie you will find 100% code coverage with tests and work under any version of PHP older than 5.3 (including the new 7 and HHVM)

    Also popular now: