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 Setup

  1. Installation Add the package via Composer in your Laravel project:

    composer require twig/string-extra
    

    Register the Twig extension in your config/view.php (or a custom Twig config file):

    'extensions' => [
        // ...
        Twig\Extra\String\StringExtension::class,
    ],
    
  2. First Use Case Use the filter or replace filters in a Twig template:

    {{ '  Hello, World!  ' | trim | title }}
    

    Output: Hello, World!

    Or in a Blade template (via @twig directive if using laravel-twig-bridge):

    @twig
        {{ 'hello@example.com' | email }}
    @endtwig
    

Implementation Patterns

Common Workflows

  1. Text Sanitization Use strip_tags or nl2br for HTML-safe text processing:

    {{ user_input | strip_tags | escape('html') }}
    
  2. URL/Email Handling Validate and format URLs/emails:

    {{ 'contact@example.com' | email | lower }}
    {{ 'https://example.com' | url | absolute_url('https://app.example.com') }}
    
  3. String Manipulation Leverage slugify, truncate, or wordwrap:

    {{ 'Laravel 10 Features' | slugify }}
    {{ long_text | truncate(50, '...') }}
    
  4. Integration with Laravel

    • Form Requests: Sanitize user input before validation:
      $cleanedInput = Str::of($request->input('bio'))->replace(['*', '#'], '');
      
    • Blade Macros: Create reusable Twig-like filters:
      Blade::directive('twigFilter', function ($expression) {
          return "<?php echo Twig\Extra\String\StringExtension::filter({$expression}); ?>";
      });
      
      Usage:
      @twigFilter('user_input | trim')
      
  5. Dynamic Filter Chaining Build reusable Twig filters in your templates:

    {% macro cleanText(text) %}
        {{ text | trim | strip_tags | escape('html') }}
    {% endmacro %}
    

Gotchas and Tips

Pitfalls

  1. Blade vs. Twig Syntax

    • The package is Twig-only. For Blade, use @twig directives or PHP-based alternatives:
      Str::of($text)->trim()->toUpper();
      
    • Avoid mixing Str::of() (Laravel) and Twig filters for the same operation (e.g., trim).
  2. Performance

    • Avoid over-filtering: Chaining multiple filters (e.g., | trim | lower | slugify) can be slow for large datasets. Pre-process in PHP when possible:
      $cleaned = Str::of($text)->lower()->slug();
      
    • Cache filtered results if reused (e.g., in loops).
  3. Locale Sensitivity

    • Some filters (e.g., title, slugify) rely on locale settings. Explicitly set locales in Twig:
      {% set app %}{{ 'app name' | title('en_US') }}{% endset %}
      
  4. Security

    • escape vs. htmlspecialchars: Prefer Twig’s escape filter over raw htmlspecialchars for consistency:
      {{ untrusted_input | escape('html') }}  {# Safe #}
      {{ untrusted_input | htmlspecialchars }} {# Less safe; may double-escape #}
      
    • XSS Risks: Always escape dynamic content before rendering, even with strip_tags.
  5. Deprecation Notes

    • Monitor Symfony String updates (this package wraps it). Example: absolute_url may change behavior if Symfony’s Url component evolves.

Tips

  1. Custom Filters Extend the package by creating a custom Twig extension:

    use Twig\TwigFilter;
    use Twig\Extension\AbstractExtension;
    
    class CustomStringExtension extends AbstractExtension
    {
        public function getFilters()
        {
            return [
                new TwigFilter('custom_filter', [$this, 'customFilter']),
            ];
        }
    
        public function customFilter($text)
        {
            return Str::of($text)->replace(['foo', 'bar'], 'baz');
        }
    }
    

    Register it in config/view.php.

  2. Debugging

    • Filter Output: Use {{ dump(text | filter) }} to inspect intermediate results.
    • Error Handling: Wrap Twig filters in Blade with @php @endphp for graceful fallbacks:
      @php
          try {
              $result = Twig\Extra\String\StringExtension::filter($text, 'nonexistent_filter');
          } catch (\Exception $e) {
              $result = $text;
          }
      @endphp
      {{ $result }}
      
  3. Configuration

    • Global Defaults: Set default Twig options in config/view.php:
      'twig' => [
          'options' => [
              'charset' => 'UTF-8',
              'auto_reload' => true,
          ],
      ],
      
    • Filter Shortcuts: Create Blade helpers for frequent filters:
      if (!function_exists('twigFilter')) {
          function twigFilter($text, $filter)
          {
              return Twig\Extra\String\StringExtension::filter($text, $filter);
          }
      }
      
      Usage:
      {{ twigFilter($text, 'slugify') }}
      
  4. Testing

    • Mock the Twig environment in PHPUnit:
      $twig = new \Twig\Environment($loader);
      $twig->addExtension(new \Twig\Extra\String\StringExtension());
      $result = $twig->render('template.twig', ['text' => $input]);
      $this->assertEquals(expected, $result);
      
  5. Performance Optimization

    • Pre-compile Filters: For static content, pre-process strings in a migration or seeder:
      DB::table('posts')->update([
          'slug' => Str::of($post->title)->slug(),
      ]);
      
    • Avoid Redundant Filters: Replace repeated filters with a single PHP operation:
      {# Less efficient #}
      {{ text | trim | lower | slugify }}
      
      {# More efficient #}
      {{ text | custom_slug }} {# Custom filter handling all steps #}
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport