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

Extra Bundle Laravel Package

twig/extra-bundle

Symfony bundle that auto-enables all Twig “extra” extensions with zero configuration. Install via Composer and instantly access additional Twig features in your Symfony app without manually registering each extension.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require twig/extra-bundle
    

    (Note: In Laravel, this alone won’t work—requires twig-laravel/twig as a bridge.)

  2. Prerequisite Setup: Install the Laravel Twig bridge:

    composer require twig-laravel/twig
    

    Publish the Twig config:

    php artisan vendor:publish --provider="Twig\Laravel\TwigServiceProvider" --tag="config"
    
  3. First Use Case: Register only non-Symfony extensions in AppServiceProvider:

    use Twig\Extra\String\StringExtension;
    use Twig\Extra\Text\TextExtension;
    
    public function boot()
    {
        $twig = app('twig');
        $twig->addExtension(new StringExtension());
        $twig->addExtension(new TextExtension());
    }
    
  4. Test in a Template: Create a Twig file (e.g., resources/views/twig/test.twig) and use extensions:

    {{ 'hello world'|upper }}          {# StringExtension #}
    {{ 'Lorem ipsum'|truncate(20, '...') }} {# TextExtension #}
    

Implementation Patterns

Usage Patterns

  1. Extension Registration:

    • Manual Registration (Recommended for Laravel):
      $twig->addExtension(new \Twig\Extra\ArrayExtension());
      $twig->addExtension(new \Twig\Extra\MarkdownExtension());
      
    • Avoid Symfony-dependent extensions (FormExtension, UrlExtension) unless mocked.
  2. Template Workflows:

    • String Manipulation:
      {{ 'example.com'|urlencode }}       {# StringExtension #}
      {{ 'Hello'|lower }}                 {# StringExtension #}
      
    • Text Processing:
      {{ 'Lorem ipsum'|truncate(10, '...') }} {# TextExtension #}
      {{ 'text'|trans }}                  {# IntlExtension (if mocked) #}
      
    • Array/Object Handling:
      {% for key, value in {'a': 1, 'b': 2}|dictsort %}
          {{ key }}: {{ value }}
      {% endfor %} {# ArrayExtension #}
      
  3. Integration with Laravel:

    • Replace Blade Helpers: Use Twig extensions instead of custom Blade directives where possible:
      {# Instead of @php Str::title($str) in Blade #}
      {{ 'hello world'|title }}
      
    • Form Handling: If using Symfony Forms, render them in Twig:
      {{ form_start(form) }}
      {{ form_widget(form.name) }}
      {{ form_end(form) }}
      
      (Requires mocking FormExtension for Laravel.)
  4. Dynamic Content:

    • Conditional Logic:
      {% if user.is_admin %}
          {{ 'Admin'|trans }}
      {% endif %}
      
    • Loops:
      {% for item in items|slice(0, 5) %}
          {{ item.name }}
      {% endfor %}
      

Workflows

  1. Hybrid Blade/Twig Projects:

    • Use Twig for complex logic (e.g., forms, localization) and Blade for simpler views.
    • Example: Admin panel in Twig, frontend in Blade.
  2. Localization:

    • Combine Laravel’s trans() with Twig’s IntlExtension:
      {{ 'welcome'|trans({'name': user.name}) }}
      {{ 'item'|pluralize(count) }}       {# IntlExtension #}
      
  3. Asset Management:

    • Replace AssetExtension with Laravel’s asset() helper:
      {% set css = asset('css/app.css') %}
      <link rel="stylesheet" href="{{ css }}">
      

Integration Tips

  1. Avoid Symfony Dependencies:

    • Skip UrlExtension, CsrfExtension, and FormExtension unless you’re using Symfony components in Laravel.
    • Mock only what’s necessary (e.g., RouterInterface for path()).
  2. Leverage Laravel’s Ecosystem:

    • Use collective/html for forms instead of FormExtension.
    • Replace AssetExtension with Blade’s @vite() or asset() helper.
  3. Testing:

    • Test Twig templates in isolation:
      $twig = app('twig');
      echo $twig->render('test.twig', ['var' => 'value']);
      
    • Ensure no conflicts with Blade’s {{ }} syntax (Twig uses {{ }} and {% %}).
  4. Configuration:

    • Extend Laravel’s Twig config (config/twig.php) to disable unwanted extensions:
      'extensions' => [
          Twig\Extra\String\StringExtension::class,
          Twig\Extra\Text\TextExtension::class,
          // Exclude Symfony extensions
      ],
      

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Conflicts:

    • The bundle pulls in Symfony components (e.g., http-kernel, form) that may clash with Laravel’s autoloader.
    • Fix: Use --ignore-platform-req=php during installation and test thoroughly.
  2. Broken Extensions:

    • Extensions like UrlExtension or CsrfExtension won’t work without Symfony’s Router or RequestStack.
    • Fix: Mock Symfony services or avoid these extensions:
      $router = new class implements \Symfony\Component\Routing\RouterInterface {
          public function generate($name, array $parameters = [], $referenceType = self::ABSOLUTE_PATH) {
              return route($name, $parameters);
          }
      };
      $twig->addExtension(new \Twig\Extra\UrlExtension($router));
      
  3. Asset Pipeline Issues:

    • AssetExtension assumes Symfony’s AssetMapper and won’t work with Laravel’s Vite/Mix.
    • Fix: Replace with:
      {% set js = asset('js/app.js') %}
      <script src="{{ js }}"></script>
      
  4. CSRF Token Conflicts:

    • Twig’s csrf_token may conflict with Blade’s @csrf or Laravel’s csrf_token() helper.
    • Fix: Use Blade’s @csrf in Blade templates and avoid CsrfExtension in Twig.
  5. Form Rendering:

    • Symfony Forms require FormExtension, which depends on Symfony’s Form component.
    • Fix: Use collective/html or Livewire for forms in Laravel.
  6. Template Caching:

    • Twig’s cache may conflict with Laravel’s view caching.
    • Fix: Configure Twig’s cache path separately:
      'cache' => storage_path('framework/views/twig'),
      

Debugging

  1. Extension Not Loading:

    • Check if the extension is registered:
      dd($twig->getExtensions());
      
    • Ensure no typos in class names (e.g., \Twig\Extra\StringExtension).
  2. Runtime Errors:

    • Symfony-dependent extensions (e.g., UrlExtension) will throw:
      Cannot instantiate interface Symfony\Component\Routing\RouterInterface
      
    • Solution: Mock the interface or remove the extension.
  3. Template Syntax Errors:

    • Twig uses {{ }} and {% %}, which may conflict with Blade’s {{ }}.
    • Fix: Use .twig extensions for Twig templates and .blade.php for Blade.
  4. Missing Functions:

    • If {{ path('route') }} fails, ensure UrlExtension is mocked:
      $twig->addExtension(new \Twig\Extra\UrlExtension($router));
      

Tips

  1. Start Small:

    • Begin with non-Symfony extensions (String, Text, Array) to avoid complexity.
    • Example:
      $twig->addExtension(new \Twig\Extra\String\StringExtension());
      $twig->addExtension(new \Twig\Extra\Text\TextExtension());
      
  2. Use Laravel Helpers:

    • Replace Twig extensions with Laravel equivalents where possible:
      Twig Extension Laravel Equivalent
      StringExtension Str::* helpers
      AssetExtension asset(), @vite()
      UrlExtension route(), url()
  3. Custom Extensions:

    • For Laravel-specific needs, create a custom Twig extension:
      use Twig\Extension\AbstractExtension;
      use Twig\TwigFunction;
      
      class LaravelExtension extends AbstractExtension
      {
          public
      
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