Installation Add the package via Composer in your Laravel project:
composer require twig/extensions
Register the extensions in your Twig environment (typically in app/Providers/AppServiceProvider.php):
use Twig\Extra\Markdown\MarkdownExtension;
use Twig\Extra\String\StringExtension;
use Twig\Extra\Markdown\Markdown;
public function register()
{
$this->app->make(\Twig\Environment::class)->addExtension(new MarkdownExtension(new Markdown()));
$this->app->make(\Twig\Environment::class)->addExtension(new StringExtension());
// Add other extensions as needed
}
First Use Case
Use the StringExtension for common string manipulations in your Twig templates:
{{ 'hello world'|upper }}
{{ 'Laravel'|title }}
{{ '123.456'|number_format(2) }}
Where to Look First
vendor/twig/extensions/src/ for extension classes and their methods.String Manipulations
Leverage StringExtension for common tasks like:
{{ 'example@test.com'|email }}
{{ '2023-10-01'|date('Y-m-d H:i') }}
{{ 'Laravel'|replace({'Laravel': 'Symfony'}) }}
Markdown Support
Use MarkdownExtension to render Markdown in templates:
{{ '# Hello World\n\nThis is **Markdown**.'|markdown }}
Configure the Markdown parser (e.g., parsedown or parsedown-extra) in your AppServiceProvider:
$this->app->make(\Twig\Environment::class)->addExtension(
new MarkdownExtension(new \ParsedownExtra())
);
Text and Intl Extensions
Use TextExtension for pluralization and IntlExtension for locale-aware formatting:
{% for i in 1..5 %}
{{ i }} {{ 'item'|pluralize(i) }}
{% endfor %}
{{ 1234.56|number_format(2, '.', ',') }}
Debugging and Profiler
Enable DebugExtension for template debugging (useful in development):
{% debug %}
Add the extension in AppServiceProvider:
$this->app->make(\Twig\Environment::class)->addExtension(new \Twig\Extensions\DebugExtension());
Lazy-Loading Extensions Register extensions conditionally based on environment or features:
if ($this->app->environment('local')) {
$this->app->make(\Twig\Environment::class)->addExtension(new \Twig\Extensions\DebugExtension());
}
Custom Filters/Functions Extend Twig with custom logic by creating a custom extension:
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class CustomExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('custom_function', [$this, 'customFunction']),
];
}
public function customFunction($input)
{
return strtoupper($input) . ' (custom)';
}
}
Register it in AppServiceProvider:
$this->app->make(\Twig\Environment::class)->addExtension(new CustomExtension());
Caching Extensions
Ensure extensions are registered before the Twig environment is cached (e.g., in bootstrap/cache). Rebuild the cache after adding new extensions:
php artisan config:cache
php artisan view:cache
Extension Conflicts
IntlExtension) require the intl PHP extension. Verify dependencies:
php -m | grep intl
StringExtension and a custom extension with overlapping filters), ensure consistent behavior by testing edge cases.Markdown Parsing Quirks
MarkdownExtension uses Parsedown, which may not support all Markdown features (e.g., tables, footnotes). Use ParsedownExtra for extended syntax:
new MarkdownExtension(new \ParsedownExtra())
{{ markdown_content|markdown|striptags }}
Performance Overhead
DebugExtension or heavy Markdown parsers can slow down template rendering. Disable them in production:
if (!$this->app->environment('local')) {
// Skip adding debug/heavy extensions
}
Twig Version Compatibility
twig/extensions package is archived and may not support the latest Twig versions. Check compatibility with your Laravel/Twig versions (e.g., Laravel 9 uses Twig 3.x). Use twig/twig for core and twig/extensions selectively.Enable Twig Debug Mode
Add this to your AppServiceProvider to debug template rendering:
$this->app->make(\Twig\Environment::class)->setDebug($this->app->environment('local'));
Inspect Available Filters/Functions Dump all available Twig functions/filters in a template:
{% set functions = _context.getFunctions() %}
{% set filters = _context.getFilters() %}
{{ dump(functions) }}
{{ dump(filters) }}
Extension Registration Order Extensions are additive. If a filter/function isn’t working, ensure:
Override Default Extensions
Replace built-in extensions (e.g., StringExtension) with a custom subclass:
class CustomStringExtension extends \Twig\Extensions\StringExtension
{
public function getFilters()
{
$filters = parent::getFilters();
$filters['custom_upper'] = [$this, 'customUpper'];
return $filters;
}
public function customUpper($string)
{
return strtoupper($string) . ' (custom)';
}
}
Add Global Variables Use extensions to inject global variables into all templates:
class GlobalVarsExtension extends AbstractExtension
{
public function getGlobals()
{
return [
'app_name' => 'MyApp',
'config' => config()->all(),
];
}
}
Test Extensions Isolated
Test extensions in isolation using Laravel’s TwigView or a standalone Twig environment:
$twig = new \Twig\Environment($loader, ['debug' => true]);
$twig->addExtension(new \Twig\Extensions\StringExtension());
echo $twig->render('template.twig', ['input' => 'test']);
How can I help you explore Laravel packages today?