Shared Variables
To share one or more variables across multiple templates, the engine provides the
shareTemplateVariable helper. This helper accepts an associative array
containing the variables you want to make globally accessible within all templates.
This is especially useful for values that should be available application-wide, such as social media links, global settings, feature flags, or authentication state.
Basic Example
Suppose you want to expose your application's social media links to every template:
shareTemplateVariable([
'githubLink' => 'https://github.com/SigmaPHP/SigmaPHP',
'docsLink' => 'https://www.sigmaphp.com/docs',
]);
The shareTemplateVariable helper can be used anywhere in your application
and may be called multiple times depending on your context or business logic.
Registering with Service Provider
In most cases, it is highly recommended to register shared template variables inside
a service provider, typically named AppServiceProvider. This ensures that
shared variables are defined in a centralized and structured way during the application boot process.
<?php
namespace App\Providers;
use SigmaPHP\Container\Interfaces\ServiceProviderInterface;
use SigmaPHP\Container\Container;
/**
* App Service Provider Class
*/
class AppServiceProvider implements ServiceProviderInterface
{
/**
* The boot method will be called after all
* dependencies are defined in the container.
*
* @param Container $container
* @return void
*/
public function boot(Container $container)
{
shareTemplateVariable([
'githubLink' => 'https://github.com/SigmaPHP/SigmaPHP',
'docsLink' => 'https://www.sigmaphp.com/docs'
]);
}
/**
* Add a definition to the container.
*
* @param Container $container
* @return void
*/
public function register(Container $container)
{
//
}
}
By registering shared variables in a service provider, you ensure consistency, maintainability, and proper separation of concerns within your application architecture.
To learn more about service providers, their lifecycle, and how they integrate with the dependency injection container, please refer to the Dependency Injection (DI) documentation page for a deeper understanding of how services are registered and bootstrapped within the application.
Using a Shared Variables
Once a variable is shared, it becomes automatically available in all templates without needing to pass it through the render method. You can access it like any other template variable and use it directly within your markup.
<a href="{{ $githubLink }}">GitHub</a>