PHP code example of dalpras / smart-template

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

    

dalpras / smart-template example snippets


echo $template['card']([
    '{title}' => 'Hello',
    '{body}' => 'Welcome',
]);



namespace App\Template;

use DalPraS\SmartTemplate\PresetInterface;
use DalPraS\SmartTemplate\TemplateEngine;

final class UiPreset implements PresetInterface
{
    public const NAMESPACE = 'ui';

    public static function register(
        TemplateEngine $engine,
        string $namespace = self::NAMESPACE,
        array $overrides = [],
        bool $default = true,
    ): TemplateEngine {
        $engine->register($namespace, [
            'card' => <<<'HTML'
<div class="card">
    <h2>{title}</h2>
    <div>{body}</div>
</div>
HTML,
        ], default: $default);

        if ($overrides !== []) {
            $engine->register($namespace, $overrides);
        }

        return $engine;
    }
}

use DalPraS\SmartTemplate\TemplateEngine;

$engine = new TemplateEngine();

UiPreset::register($engine);

echo $engine->renderDefault(function ($ui) {
    return $ui['card']([
        '{title}' => 'Hello',
        '{body}' => 'This is rendered with Smart Template.',
    ]);
});

$engine = new TemplateEngine();

UiPreset::register($engine);

echo $engine->render('ui', function ($ui) {
    return $ui['card']([
        '{title}' => 'Hello',
        '{body}' => 'Preset rendering',
    ]);
});

$ui = $engine->collection();

echo $ui['card']([
    '{title}' => 'Hello',
    '{body}' => 'Default collection',
]);

$engine->register('ui', $templates, default: true);

use DalPraS\SmartTemplate\PresetInterface;
use DalPraS\SmartTemplate\TemplateEngine;
use DalPraS\SmartTemplate\Collection\RenderCollection;

final class HtmlPreset implements PresetInterface
{
    public const NAMESPACE = 'html';

    public static function register(
        TemplateEngine $engine,
        string $namespace = self::NAMESPACE,
        array $overrides = [],
        bool $default = true,
    ): TemplateEngine {
        $templates = $engine->   ): RenderCollection {
        return $engine->collection($namespace);
    }

    public static function path(): string
    {
        return dirname(__DIR__, 2) . '/resources/templates/html.php';
    }
}

$engine = new TemplateEngine();

HtmlPreset::register($engine);

$html = $engine->collection();

echo $html['div']([
    '{attributes}' => 'class="box"',
    '{body}' => 'Hello',
]);

HtmlPreset::register($engine, namespace: 'html', default: false);

echo $engine->render('html', function ($html) {
    return $html['div']([
        '{attributes}' => 'class="box"',
        '{body}' => 'Hello',
    ]);
});

final class UiPreset implements PresetInterface
{
    public const NAMESPACE = 'ui';

    public static function register(
        TemplateEngine $engine,
        string $namespace = self::NAMESPACE,
        array $overrides = [],
        bool $default = true,
    ): TemplateEngine {
        $templates = $engine->ter($namespace, $overrides);
        }

        return $engine;
    }

    public static function path(): string
    {
        return dirname(__DIR__, 2) . '/templates/default.php';
    }

    public static function collection(
        TemplateEngine $engine,
        ?string $namespace = self::NAMESPACE,
    ): RenderCollection {
        return $engine->collection($namespace);
    }
}

$engine = new TemplateEngine();

UiPreset::register($engine);

$ui = $engine->collection();

echo $ui['button']([
    '{label}' => 'Save',
]);

$templates = $engine->ates)) {
    throw new RuntimeException('Template file must return an array.');
}

$engine->register('ui', $templates);



return [
    'card' => <<<'HTML'
<div class="card">
    <h2>{title}</h2>
    <div>{body}</div>
</div>
HTML,

    'button' => <<<'HTML'
<button>{label}</button>
HTML,
];

$engine->register('ui', [
    'button' => '<button>{label}</button>',
]);

$engine->register('ui', [
    'card' => '<div class="card">{body}</div>',
]);

$engine->register('ui', [
    'button' => '<button class="btn">{label}</button>',
]);

$ui = $engine->collection('ui');

echo $ui['button']([
    '{label}' => 'Save',
]);

echo $ui['card']([
    '{body}' => 'Hello',
]);

register('new_namespace', $templates);      // create
register('existing_namespace', $templates); // merge or override

$engine->register('ui', [
    'title' => '<h1>{text}</h1>',
]);

$ui = $engine->collection();

echo $ui['title']([
    '{text}' => 'Hello',
]);

$engine->setDefaultNamespace('ui');

$ui = $engine->defaultCollection();

$engine->register('mail', [
    'layout' => [
        'page' => <<<'HTML'
{header}
{content}
HTML,
    ],

    'partials' => [
        'title' => '<h1>{text}</h1>',
    ],
]);

$mail = $engine->collection('mail');

echo $mail['layout']['page']([
    '{header}' => $mail['partials']['title']([
        '{text}' => 'Newsletter',
    ]),
    '{content}' => '<p>Welcome.</p>',
]);



return [
    'layout' => [
        'page' => '{content}',
    ],

    'partials' => $this->lazyRequire(__DIR__ . '/partials.php'),
];



return [
    'title' => '<h1>{text}</h1>',
    'paragraph' => '<p>{text}</p>',
];

echo $engine->render('mail', function ($mail) {
    return $mail['layout']['page']([
        '{header}' => fn ($root) => $root['partials']['title']([
            '{text}' => 'Newsletter',
        ]),
        '{content}' => '<p>Welcome.</p>',
    ]);
});

'{content}' => function ($root, $scope, $engine, $namespace) {
    return $root['partials']['paragraph']([
        '{text}' => 'Generated lazily',
    ]);
}

echo '<input ' . $engine->attributes([
    'id' => 'user[email]',
    'name' => 'user[email]',
    'title' => 'Email address',
    'class' => 'form-control',
]) . '>';

echo '<button ' . $engine->attributes([
    'class' => fn () => 'btn btn-primary',
    'title' => fn () => 'Save changes',
]) . '>Save</button>';

$engine->addCustomParamCallback(
    '{attributes}',
    static function ($value) use ($engine): string {
        return $value === null ? '' : $engine->attributes((array) $value);
    }
);

$engine->addCustomParamCallback(
    '{class}',
    static fn ($value): string => $value === null ? '' : trim((string) $value)
);

$engine->register('ui', [
    'button' => '<button {attributes}>{label}</button>',
]);

echo $engine->collection('ui')['button']([
    '{attributes}' => [
        'type' => 'button',
        'class' => 'btn btn-primary',
    ],
    '{label}' => 'Save',
]);

$engine->register('ui', [
    'title' => '<h2 class="{class}">{content}</h2>',
]);

$engine->addCustomParamModifier(
    'upperCase',
    static fn (mixed $value): string => mb_strtoupper((string) $value, 'UTF-8')
);

echo $engine->collection('ui')['title']([
    '{class}' => 'fs-3',
    '{content}|upperCase' => 'hello world',
]);

[
    '{content}|upperCase' => 'hello world',
]

[
    '{content}' => 'HELLO WORLD',
]

$engine->addCustomParamModifier(
    'trim',
    static fn (mixed $value): string => trim((string) $value)
);

$engine->addCustomParamModifier(
    'upperCase',
    static fn (mixed $value): string => mb_strtoupper((string) $value, 'UTF-8')
);

echo $engine->collection('ui')['title']([
    '{class}' => 'fs-3',
    '{content}|trim|upperCase' => ' hello world ',
]);

$engine->addCustomParamModifier(
    'primaryButton',
    static function (mixed $value): array {
        $attributes = is_array($value) ? $value : [];

        $attributes['class'] = trim(($attributes['class'] ?? '') . ' btn btn-primary');

        return $attributes;
    }
);

$engine->addCustomParamCallback(
    '{attributes}',
    static fn (mixed $value): string => $value === null
        ? ''
        : $engine->attributes((array) $value)
);

$engine->register('ui', [
    'button' => '<button {attributes}>{content}</button>',
]);

echo $engine->collection('ui')['button']([
    '{attributes}|primaryButton' => [
        'type' => 'submit',
    ],
    '{content}' => 'Save',
]);

$engine->register('ui', [
    'title' => '<h2>%content%</h2>',
]);

echo $engine->collection('ui')['title']([
    '%content%|upperCase' => 'hello world',
]);

'{content}|upperCase'
'%content%|upperCase'
'[[content]]|upperCase'
':content:|upperCase'
'{{ content }}|upperCase'

|

echo $engine->collection('ui')['title']([
    '{content}|upperCase' => 'hello world',
]);

$engine->setCustomParamModifierSeparator('::');

echo $engine->collection('ui')['title']([
    '{content}::upperCase' => 'hello world',
]);

echo $engine->collection('ui')['title']([
    '{content}::trim::upperCase' => ' hello world ',
]);

$engine->register('icons', [
    'save' => '<span>{content}</span>',
]);

$engine->register('ui', [
    'button' => '<button>{icon}{label}</button>',
]);

echo $engine->render('ui', function ($ui) use ($engine) {
    return $ui['button']([
        '{icon}' => $engine->collection('icons')['save']([
            '{content}' => '...',
        ]),
        '{label}' => 'Save',
    ]);
});

$engine->register('demo', [
    'line' => '<p>{value}</p>',
]);

$demo = $engine->collection('demo');

echo $demo['line']([
    '{value}' => new DateTimeImmutable('2026-03-24 10:00:00'),
]);

try {
    $tpl = $engine->collection('missing');
} catch (\Throwable $e) {
    // log or recover
}

try {
    $templates = $engine->/ log or recover
}

final class UiPreset implements PresetInterface
{
    public const NAMESPACE = 'ui';

    public static function register(
        TemplateEngine $engine,
        string $namespace = self::NAMESPACE,
        array $overrides = [],
        bool $default = true,
    ): TemplateEngine {
        $templatesDir = dirname(__DIR__) . '/templates';

        $templates = $engine->



return [
    'layout' => [
        'page' => '{content}',
    ],

    'partials' => $this->lazyRequire(__DIR__ . '/partials.php'),
];



return [
    'title' => '<h1>{text}</h1>',
];

new TemplateEngine()

render(string $namespace, Closure $callback): mixed
renderDefault(Closure $callback): mixed

collection(?string $namespace = null): RenderCollection
defaultCollection(): RenderCollection
hasCollection(string $namespace): bool

register(string $namespace, array|RenderCollection $templates, bool $default = false): static
setDefaultNamespace(string $namespace): static
getDefaultNamespace(): ?string

ator(string $separator): static
getCustomParamModifierSeparator(): string

public static function register(
    TemplateEngine $engine,
    string $namespace = '',
    array $overrides = [],
    bool $default = true,
): TemplateEngine;

$ui = $engine->collection('ui');

echo $ui['button']([
    '{label}' => 'Save',
]);

$engine = new TemplateEngine(
    directory: $templatesDir,
    default: 'default.php',
    preload: true,
);

$engine->render('default.php', ...);

$engine = new TemplateEngine();

UiPreset::register($engine);

$engine->renderDefault(...);

$engine->render('ui', ...);

// Avoid
public const NAMESPACE = 'default.php';

// Prefer
public const NAMESPACE = 'ui';
text
src/
|-- Template/
|   `-- UiPreset.php
`-- templates/
    |-- default.php
    `-- partials.php