Custom Directives
Sometimes applications require additional logic inside templates, such as formatting currency, handling order statuses, or transforming data before displaying it. SigmaPHP-Template allows you to extend the template language by defining custom directives.
Custom directives are registered using the defineCustomTemplateDirective global helper. A directive
follows the syntax {% myDirective(...) %}, where the directive name maps to a PHP callback that may
accept parameters and return a value to be rendered by the engine.
Registering a Custom Directive
<?php
defineCustomTemplateDirective('currency', function ($amount) {
return '$' . number_format($amount, 2);
});
defineCustomTemplateDirective('orderStatus', function ($status) {
if ($status === 'paid') {
return 'Paid';
}
if ($status === 'pending') {
return 'Pending';
}
return 'Unknown';
});
Registering Directives in a Service Provider
Custom directives are typically registered inside a service provider so they are available across the entire
application. A common place for this logic is the AppServiceProvider.
<?php
namespace App\Providers;
use SigmaPHP\Container\Interfaces\ServiceProviderInterface;
use SigmaPHP\Container\Container;
class AppServiceProvider implements ServiceProviderInterface
{
public function boot(Container $container)
{
defineCustomTemplateDirective('currency', function ($amount) {
return '$' . number_format($amount, 2);
});
}
public function register(Container $container)
{
//
}
}
Using a Custom Directive in Templates
Once registered, the directive can be used directly inside templates using the directive syntax.
<p>Total: {% currency(199.5) %}</p>
<p>Order Status: {% orderStatus('paid') %}</p>