Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

String Extra Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Add the package and Symfony's string component via Composer:

    composer require twig/string-extra symfony/string:^6.0
    

    Note: Pin symfony/string to ^6.0 to avoid conflicts with Laravel's default dependencies.

  2. Blade Integration (Quick Start) Register a custom Blade directive in app/Providers/AppServiceProvider.php:

    use Illuminate\Support\Facades\Blade;
    
    public function boot()
    {
        Blade::directive('slugify', function ($expression) {
            return "<?php echo \\Symfony\\Component\\String\\UnicodeString::from({$expression})->slug(); ?>";
        });
    }
    

    Usage in Blade:

    <a href="/{{ $post->title | slugify }}">{{ $post->title }}</a>
    
  3. First Use Case Generate SEO-friendly URLs for blog posts:

    <h1>{{ $post->title }}</h1>
    <p>URL: <code>/posts/{{ $post->title | slugify }}</code></p>
    

    Output: URL: <code>/posts/laravel-twig-string-extra-guide</code>


Implementation Patterns

Core Workflows

  1. Slug Generation

    • Blade: {{ $title | slugify }}
    • Twig: {{ 'Hello World' | slug }}
    • Use Case: Dynamic routes, meta tags, or file names.
    • Example:
      <meta property="og:url" content="https://example.com/{{ $post->title | slugify }}">
      
  2. Pluralization/Singularization

    • Blade: {{ $count }} {{ 'item' | pluralize }}
    • Twig: {{ 5 | plural('item') }}
    • Use Case: Localized labels, UI feedback.
    • Example:
      {{ $count }} {{ 'notification' | pluralize }}
      
      Output: 5 notifications
  3. Text Wrapping (UnicodeString)

    • Blade: {{ $text | unicodeString | titlecase }}
    • Twig: {{ 'café' | u | titlecase }}
    • Use Case: Formatting user-generated content.
    • Example:
      <h2>{{ $userInput | unicodeString | capitalize }}</h2>
      

Integration Tips

  • Laravel Form Requests Combine with Symfony’s String for input sanitization:

    // app/Http/Requests/SanitizeInput.php
    public function rules()
    {
        return ['title' => 'required|string'];
    }
    
    public function sanitize($input)
    {
        return \Symfony\Component\String\UnicodeString::from($input)
            ->trim()
            ->lowercase();
    }
    

    Template Usage:

    <input type="text" value="{{ $sanitizedTitle | titlecase }}">
    
  • Dynamic Meta Tags Generate og:title and og:description in Blade:

    <meta property="og:title" content="{{ $post->title | truncate(60) }}">
    <meta property="og:description" content="{{ $post->excerpt | truncate(150) }}">
    
  • Localization Use with Laravel’s Str::of() for multilingual support:

    {{ $translatedText | slug }}  <!-- e.g., "Café" → "cafe" -->
    
  • Caching Strategies Cache slugs in a model method to avoid repeated template processing:

    // app/Models/Post.php
    public function getSlugAttribute()
    {
        return cache()->remember("post-slug-{$this->id}", now()->addHours(1), function () {
            return \Symfony\Component\String\UnicodeString::from($this->title)->slug();
        });
    }
    

    Template:

    <a href="/{{ $post->slug }}">{{ $post->title }}</a>
    

Gotchas and Tips

Pitfalls

  1. Symfony Version Conflicts

    • Issue: Laravel may pull in symfony/string:^5.4. The package requires ^6.0.
    • Fix: Add to composer.json:
      "conflict": {
          "symfony/string": "6.0.*"
      }
      
    • Alternative: Use replace if conflicts persist:
      "replace": {
          "symfony/string": "6.0.0"
      }
      
  2. Blade Directive Caching

    • Issue: Custom directives may break Laravel’s view caching.
    • Fix: Clear cached views after adding directives:
      php artisan view:clear
      
    • Debug: Check storage/framework/views for compiled files.
  3. Unicode Edge Cases

    • Issue: Non-ASCII characters may not slug as expected (e.g., Cafécafe-au-lait).
    • Fix: Test with real-world data:
      $slug = \Symfony\Component\String\UnicodeString::from('Café au lait')->slug();
      // Output: "cafe-au-lait"
      
  4. Performance in Loops

    • Issue: Processing strings in template loops (e.g., {{ $items | map('slugify') }}) is slow.
    • Fix: Offload to PHP:
      // Controller
      $items = collect($items)->map(fn ($item) => [
          'slug' => \Symfony\Component\String\UnicodeString::from($item->title)->slug(),
      ]);
      
      Template:
      @foreach($items as $item)
          <a href="/{{ $item->slug }}">{{ $item->title }}</a>
      @endforeach
      
  5. Twig vs. Blade Syntax

    • Issue: Mixing | slug (Twig) and slugify() (Blade) can confuse teams.
    • Fix: Standardize on one approach (e.g., Blade directives for consistency).

Debugging Tips

  • Check Registered Directives Dump Blade directives to verify registration:

    dd(collect(Blade::$directives)->keys()->all());
    
  • Symfony String Methods Explore all available methods:

    $string = \Symfony\Component\String\UnicodeString::from('Hello World');
    $string->titlecase(); // "Hello World"
    $string->camelcase(); // "helloWorld"
    $string->snakeCase(); // "hello_world"
    
  • Fallback for Missing Packages If twig/string-extra fails, use Symfony’s String directly in Blade:

    {{ \Symfony\Component\String\UnicodeString::from($text)->slug() }}
    

Extension Points

  1. Custom Filters Extend the StringExtension for project-specific needs:

    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    
    class CustomStringExtension extends AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new TwigFunction('custom_slug', [$this, 'customSlug']),
            ];
        }
    
        public function customSlug($text)
        {
            return \Symfony\Component\String\UnicodeString::from($text)
                ->slug()
                ->prepend('custom-');
        }
    }
    

    Register in config/twig.php:

    'extensions' => [
        \Twig\Extra\String\StringExtension::class,
        App\Extensions\CustomStringExtension::class,
    ],
    
  2. Blade Macros Create reusable macros for complex operations:

    Blade::macro('seoSlug', function ($text) {
        return \Symfony\Component\String\UnicodeString::from($text)
            ->slug()
            ->lower();
    });
    

    Usage:

    <meta property="og:url" content="/{{ seoSlug($post->title) }}">
    
  3. Form Request Integration Combine with Laravel’s Form Requests for input sanitization:

    // app/Http/Requests/SanitizeTitle.php
    public function rules()
    {
        return ['title' => 'required|string'];
    }
    
    public function prepareForValidation()
    {
        $this->merge([
            'title' => \Symfony\Component\String\UnicodeString::from($this->title)
                ->trim()
                ->titlecase(),
        ]);
    }
    

    Template:

    <h1>{{ $request->title }}</h1>  <!-- Already sanitized -->
    

Configuration Quirks

  • **Twig Auto
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony