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.
Available Directives
current
Returns the current request URL. This helper is useful when you need to access or display the active route within your templates.
{% current() %}
previous
Retrieves the previous request URL. Commonly used for navigation purposes, such as creating “back” links or redirecting users to their last visited page.
{% previous() %}
cookie
Fetches the value of a cookie by its name. This helper simplifies accessing client-stored data directly within your templates.
{% cookie('user_preference') %}
session
Retrieves a value from the session using the provided key. Useful for accessing user-specific data such as authentication details or temporary messages.
{% session('user_id') %}
method
Generates a hidden input field used to spoof HTTP methods in HTML forms. This is particularly useful when working with methods such as PUT, PATCH, or DELETE, which are not natively supported by standard HTML forms.
{% method('PUT') %}
asset
Generates a full URL for a static asset based on the configured assets route.
{% asset('css/app.css') %}
Registering a Custom Directive
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.
<?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>