twig/string-extra
Twig extension integrating Symfony String: add filters u (UnicodeString methods), slug (AsciiSlugger), and singular/plural (Inflector) to manipulate text, generate slugs, and handle basic inflection directly in Twig templates.
Installation Add the package and Symfony String component to your Laravel project:
composer require twig/string-extra symfony/string
Register the Extension
If using Twig (via laravel-twig package), add the extension in config/twig.php:
'extensions' => [
\Twig\Extra\String\StringExtension::class,
],
If using Blade, create a custom directive in a service provider:
use Symfony\Component\String\UnicodeString;
Blade::directive('slugify', function ($expression) {
return "<?php echo app(UnicodeString::class)->from({$expression})->slug(); ?>";
});
First Use Case In a Twig template:
{{ 'Laravel is Awesome!' | slugify }}
Output: laravel-is-awesome
In a Blade template:
@slugify($post->title)
String Filtering Use built-in filters for common operations:
{{ ' hello ' | trim | title }} {# "Hello" #}
{{ 'Laravel' | snake_case }} {# "laravel" #}
{{ '1000' | int }} {# 1000 #}
Slug Generation Generate SEO-friendly URLs:
{{ 'Laravel 10 Features' | slugify }} {# "laravel-10-features" #}
Text Truncation Limit text length with ellipsis:
{{ 'This is a long text...' | truncate(10, '...') }}
{# "This is a..." #}
Unicode Handling Normalize and manipulate Unicode strings:
{{ 'Café' | ascii }} {# "Cafe" #}
{{ 'café' | title }} {# "Café" #}
Custom Directives Extend Blade with Symfony String methods:
// app/Providers/AppServiceProvider.php
use Symfony\Component\String\UnicodeString;
public function boot()
{
Blade::directive('slugify', function ($expression) {
return "<?php echo app(UnicodeString::class)->from({$expression})->slug(); ?>";
});
}
Usage:
<a href="/@slugify($post->title)">{{ $post->title }}</a>
Helper Functions
Create reusable helpers in app/Helpers/StringHelper.php:
if (!function_exists('slugify')) {
function slugify($string)
{
return UnicodeString::from($string)->slug();
}
}
Register in AppServiceProvider:
require app_path('Helpers/StringHelper.php');
Usage:
<a href="/{{ slugify($post->title) }}">{{ $post->title }}</a>
Form Input Sanitization Clean user input before processing:
@php
$cleanedInput = UnicodeString::from($request->input('bio'))
->replace(['*', '#'], '')
->trim();
@endphp
Model Accessors Use the package in Eloquent model accessors:
// app/Models/Post.php
public function getSlugAttribute()
{
return UnicodeString::from($this->title)->slug();
}
Usage in Blade:
<a href="/{{ $post->slug }}">{{ $post->title }}</a>
Request Validation Sanitize input during validation:
use Symfony\Component\String\UnicodeString;
$validated = $request->validate([
'title' => 'required|string',
]);
$validated['slug'] = UnicodeString::from($validated['title'])->slug();
API Responses Format responses with consistent string handling:
return response()->json([
'title' => $post->title,
'slug' => UnicodeString::from($post->title)->slug(),
]);
Blade Directive Caching
php artisan view:clear
Symfony Version Conflicts
symfony/string is compatible with your Laravel version. Laravel 10+ works with Symfony 6.x:
composer require symfony/string:^6.0
composer.json:
"conflict": {
"symfony/*": "6.*"
}
Unicode Edge Cases
slugify) may not handle all Unicode characters as expected. Test with non-ASCII input:
{{ 'Café au Lait' | slugify }} {# "cafe-au-lait" #}
Performance in Loops
{{ item | slugify }} for 1000 items). Offload to the controller:
// Controller
$items = $items->map(fn ($item) => [
'slug' => UnicodeString::from($item->title)->slug(),
'title' => $item->title,
]);
Twig vs. Blade Syntax
| for filters (e.g., {{ 'text' | slugify }}), while Blade uses @directives (e.g., @slugify($var)). Mixing them requires careful setup.Check Registered Extensions Verify the Twig extension is loaded:
// In a Twig template
{{ dump(app('twig')->getExtensions()) }}
Look for \Twig\Extra\String\StringExtension.
Blade Directive Debugging If a directive fails silently, add error handling:
Blade::directive('slugify', function ($expression) {
try {
return "<?php echo app(UnicodeString::class)->from({$expression})->slug(); ?>";
} catch (\Exception $e) {
return "<?php echo 'ERROR: ' . htmlspecialchars($e->getMessage()); ?>";
}
});
Symfony String Methods Explore available methods in the Symfony String documentation. Example:
{{ 'Laravel' | camel_case }} {# "laravel" #}
{{ 'laravel' | upper_case }} {# "LARAVEL" #}
{{ 'Laravel' | lower_case }} {# "laravel" #}
Custom Filters Extend the Twig extension by creating a custom filter:
use Twig\TwigFilter;
use Symfony\Component\String\UnicodeString;
$twig->addFilter(new TwigFilter('custom_slug', function ($string) {
return UnicodeString::from($string)->slug()->lower();
}));
Usage:
{{ 'Hello World' | custom_slug }} {# "hello-world" #}
Blade Macro Extensions Add string methods to Blade components:
use Illuminate\Support\Facades\Blade;
use Symfony\Component\String\UnicodeString;
Blade::extend(function ($value) {
$value->slugify = function ($expression) {
return "<?php echo app(UnicodeString::class)->from({$expression})->slug(); ?>";
};
return $value;
});
Laravel Facade Create a facade for global access:
// app/Facades/StringFacade.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
use Symfony\Component\String\UnicodeString;
class StringFacade extends Facade
{
protected static function getFacadeAccessor()
{
return UnicodeString::class;
}
}
Register in AppServiceProvider:
$this->app->singleton(UnicodeString::class, function () {
return new UnicodeString('');
});
Usage:
use App\Facades\String;
$slug = String::from($title)->slug();
How can I help you explore Laravel packages today?