PHP code example of daycry / twig

1. Go to this page and download the library: Download daycry/twig 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/ */

    

daycry / twig example snippets


$config->toolbarMinimal = true; // only essential metrics

$config->toolbarMinimal = false;
$config->toolbarShowTemplates = false;

$config->leanMode = true;
$config->enableDiscoverySnapshot = true; // snapshot only; warmupSummary, invalidations, metrics stay OFF

$twig->listTemplates(true); // [['name'=>'welcome','compiled'=>true], ...]

$twig->warmup(['welcome']);
print_r($twig->getDiagnostics()['warmup']);

$config = new \Daycry\Twig\Config\Twig();

// Optional: enable strict variables (throw on undefined)
$config->strictVariables = true;

// Optional: Lean Mode (disable non-essential persistence & diagnostics)
$config->leanMode = true;                      // minimal overhead
$config->enableDiscoverySnapshot = true;       // re-enable snapshot in lean if you have many templates

// Custom template paths (optionally with namespace)
$config->paths = [APPPATH.'Module/Views', [APPPATH.'Admin/Views','admin']];

// Create instance
$twig = new \Daycry\Twig\Twig($config);

$twig = new \Daycry\Twig\Twig();
$twig->display( 'file.html', [] );


$twig = \Config\Services::twig();
$twig->display( 'file.html', [] );


protected $helpers = [ 'twig_helper' ];

// Same instance as Services::twig()
$twig = twig_instance();
$twig->display('file.html', []);

// Render-and-return / render-and-echo without resolving the service by hand
$html = twig_render('emails/welcome', ['name' => 'Daycry']);
twig_display('layout/main', ['title' => 'Home']);

// Capture stdout from a callable as a string
$captured = twig_capture(static fn () => twig_display('partials/sidebar'));

$twig = new \Daycry\Twig\Twig();

$session = \Config\Services::session();
$session->set( array( 'name' => 'Daycry' ) );
$twig->addGlobal( 'session', $session );
$twig->display( 'file.html', [] );



<!DOCTYPE html>
<html lang="es">  
    <head>    
        <title>Example</title>    
        <meta charset="UTF-8">
        <meta name="title" content="Example">
        <meta name="description" content="Example">   
    </head>  
    <body>
        <h1>Hi {{ name }}</h1>
        {{ dump( session.get( 'name' ) ) }}
    </body>  
</html>



    use Daycry\Twig\Debug\Toolbar\Collectors\Twig;
    
    public array $collectors = [
        ...
        //Views::class,
        Twig::class
    ];


$config->leanMode = true; // disables warmup summary, invalidation history, discovery snapshot, dynamic & extended diagnostics

$config->leanMode = true;
$config->enableDiscoverySnapshot = true;   // keep snapshot for faster discovery
$config->enableWarmupSummary = true;       // record last warmup result

use Twig\\Loader\\ArrayLoader;
use Daycry\\Twig\\Twig;

$twig = new Twig();
$twig->withLoader(new ArrayLoader([
    'hello.twig' => 'Hello {{ name }}'
]));

echo $twig->render('hello', ['name' => 'World']);

$config = new \\Daycry\\Twig\\Config\\Twig();
$config->strictVariables = true;
$twig = new Twig($config);

// Boolean shorthand
$twig->registerFunction('hello_fn', fn(string $n) => 'Hello ' . $n);             // escaped by default
$twig->registerFunction('raw_html', fn() => '<b>Bold</b>', true);                // mark as safe HTML

// Array options (new)
$twig->registerFunction('upper_env',
    function(\Twig\Environment $env, string $v) { return strtoupper($v); },
    ['needs_environment' => true]
);

// Filters
$twig->registerFilter('exclaim', fn(string $v) => $v . '!', ['is_safe' => ['html']]);
$twig->registerFilter('italic', fn(string $v) => '<i>'.$v.'</i>', []);           // will be escaped

$config = new \\Daycry\\Twig\\Config\\Twig();
$config->cachePath = WRITEPATH.'cache'.DIRECTORY_SEPARATOR.'twig_custom';
$twig = new Twig($config);

$removedFiles = $twig->clearCache();       // remove compiled files only
$removedFiles = $twig->clearCache(true);   // also reset Twig Environment
$cacheDir     = $twig->getCachePath();

$config = new \\Daycry\\Twig\\Config\\Twig();
$config->strictVariables = true;
$config->cachePath = WRITEPATH.'cache/twig_app';

$twig = new Twig($config);

$twig->registerFunction('link', fn(string $t, string $u) => '<a href="'.esc($u,'url').'">'.esc($t).'</a>', true);
$twig->registerFilter('reverse', fn(string $v) => strrev($v));

echo $twig->render('page', ['title' => 'My Page']);

use Daycry\Twig\Twig;
use App\Twig\MyExtension; // extends \Twig\Extension\AbstractExtension

$twig = new Twig();
$twig->registerExtension(MyExtension::class); // queued or immediate

$twig->invalidateTemplate('emails/welcome');           // best-effort removal
$twig->invalidateTemplate('emails/welcome', true);     // remove + reinitialize environment

$summary = $twig->invalidateTemplates(['welcome','emails/welcome','admin/dashboard']);
/* $summary example:
[
    'removed'   => 3,        // total cache files removed
    'templates' => [         // per logical template details
        'welcome' => 1,
        'emails/welcome' => 1,
        'admin/dashboard' => 1,
    ],
    'reinit' => false,
]*/

// Force environment recreation after invalidation:
$twig->invalidateTemplates(['welcome'], true);

// Invalidate all templates under namespace '@admin'
$twig->invalidateNamespace('@admin');

// Invalidate all templates in the main (root) namespace
$twig->invalidateNamespace(null);

// Specific templates (logical names without extension)
$summary = $twig->warmup(['welcome','emails/welcome']);
// All discovered templates under configured paths
$summaryAll = $twig->warmupAll();

/* Returned structure:
[
    'compiled' => 5,
    'skipped'  => 12, // already compiled
    'errors'   => 0,
]
*/

// Force recompilation ignoring existing compiled cache fingerprints
$twig->warmup(['welcome'], true);

use Psr\Log\LoggerInterface;

/** @var LoggerInterface $logger */
$twig = new \Daycry\Twig\Twig($config, $logger);
// or later:
$twig->setLogger($logger);
$twig->setLogger(null); // restore the log_message() fallback

use Daycry\Twig\Constants\TwigEvent;

event(TwigEvent::WarmupAfter->value, $payload);

// All templates
$all = $twig->listTemplates();

// All templates inside a namespace
$admin = $twig->listTemplates(false, '@admin');

// Pattern filtering (within namespace)
$adminDash = $twig->listTemplates(false, '@admin', 'dash*/index');

// With compiled status
$withStatus = $twig->listTemplates(true);

$twig->unregisterFunction('temp_fn');
$twig->unregisterFilter('brackets');
$twig->unregisterExtension(MyExtension::class);

$twig->disableCache();          // turns off cache (does not delete existing by default)
$twig->disableCache(true);      // also removes existing compiled files
$twig->enableCache();           // re-enable with default path
$twig->enableCache('/custom/path');
if (! $twig->isCacheEnabled()) { /* ... */ }

$twig->setAutoescapeForNamespace('admin', 'html');
$twig->setAutoescapeForNamespace('rawmail', false);   // disable escaping
$twig->removeAutoescapeForNamespace('rawmail');

$twig->warmup(['welcome']);
$templates = $twig->listTemplates(true); // [['name' => 'welcome', 'compiled' => true], ...]

$diag = $twig->getDiagnostics();
print_r($diag['performance']['per_template']);
print_r($diag['performance']['top_templates']); // top 10 by total ms

php spark twig:clear-cache --reinit

php spark twig:clear-cache
php spark twig:clear-cache --reinit   # also recreates the Environment

php spark twig:invalidate emails/welcome
php spark twig:invalidate emails/welcome --reinit

php spark twig:warmup --all
php spark twig:warmup welcome emails/welcome
php spark twig:warmup welcome --force   # recompile even if cached