PHP code example of maurice2k / zenplate

1. Go to this page and download the library: Download maurice2k/zenplate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maurice2k / zenplate example snippets


use Maurice\Zenplate\Runner;

$runner = new Runner();
$runner->assign('name', 'Alice');

echo $runner->run('Hello {%name}!');
// => Hello Alice!

$runner->assign([
    'subject' => 'Welcome',
    'user'    => ['name' => 'Alice', 'role' => 'admin'],
]);

$runner->assign('name', 'world');
$runner->run('Hello {%name}!');
// => Hello world!

$runner->assign('user', ['name' => 'Bob', 'role' => 'admin']);
$runner->run('{%user.name} ({%user.role})');
// => Bob (admin)

$runner->assign('cfg', ['feature' => ['enabled' => true]]);
$runner->run('{%cfg.feature.enabled}');         // => 1
$runner->run('{%cfg.feature.does.not.exist}');  // => (empty)

$runner->assign('items', ['first', 'second', 'third']);
$runner->run('{%items[1]}');               // => second

$runner->assign('data', ['foo' => 'bar']);
$runner->run('{%data["foo"]}');            // => bar

$runner->assign('users', [
    'admins' => [
        ['name' => 'Alice'],
        ['name' => 'Bob'],
    ],
]);
$runner->run('{%users.admins[1].name}');   // => Bob

$runner->assign('status', 'active');

$runner->run('{if %status == "active"}on{else}off{/if}');
// => on

$tpl = '{if %n == 1}one{elseif %n == 2}two{elseif %n == 3}three{else}other{/if}';
$runner->assign('n', 2);
$runner->run($tpl); // => two

$runner->run('{if %show}visible{/if}');

$runner->assign('a', true);
$runner->assign('b', false);
$runner->run('{if (%a && !%b) || %b}hit{else}miss{/if}'); // => hit

$runner->assign('s', 'hello');
$runner->run('{if strlen(%s) > 3}long{else}short{/if}'); // => long

use Maurice\Zenplate\Compiler;

$c = new Compiler();
$c->supportedIfFuncs[] = 'count';

use Maurice\Zenplate\Compiler;

$c = new Compiler();
$c->leftDelimiter  = '<<';
$c->rightDelimiter = '>>';

$compiled = $c->compile('Hello <<%name>>!');

use Maurice\Zenplate\Compiler;
use Maurice\Zenplate\Runner;

$compiled = (new Compiler())->compile('Hello {%name}!');
file_put_contents('/var/cache/greeting.php', $compiled);

// Later, possibly in another request:
$runner = new Runner();
$runner->assign('name', 'Alice');
echo $runner->runCompiled(file_get_contents('/var/cache/greeting.php'));

use Maurice\Zenplate\Exception\ExecuteException;

try {
    $runner->run('{if %x == }nope{/if}');
} catch (ExecuteException $e) {
    // "Error compiling template; error messages: ..."
}

$c = new Compiler();
if ($c->compile($tpl) === false) {
    foreach ($c->getErrors() as $err) {
        // $err = ['type' => int, 'offset' => int, 'additional' => string, 'message' => string]
    }
}