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 (twig/extra-bundle) to add optional Twig features to your app quickly, keeping setup minimal and consistent across environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require twig/extra-bundle
    

    Register the bundle in config/bundles.php (Symfony 4.3+ auto-discovers it).

  2. First Use Case: Enable the Twig_ExtraBundle in config/packages/twig.yaml (if not auto-loaded):

    twig:
        extra_bundle:
            enabled: true
    

    Verify by using a built-in extension in a Twig template:

    {{ 'hello'|upper }}
    

    (Renders HELLO due to the StringExtension.)

  3. Key Files to Check:

    • config/packages/twig.yaml (for bundle configuration).
    • templates/ (for testing extensions in templates).
    • Symfony’s var/cache/dev/ (for debugging compiled Twig).

Implementation Patterns

Common Workflows

  1. String Manipulation: Use StringExtension for common text operations:

    {{ 'user@example.com'|email_address }}  {# Formats as "User <user@example.com>" #}
    {{ '2023-10-01'|date('Y-m-d H:i') }}    {# Converts to full datetime #}
    
  2. URL Generation: Leverage UrlExtension for dynamic links:

    {{ path('app_home') }}                  {# Generates route URL #}
    {{ url('https://example.com')|absolute_url }}  {# Converts to absolute URL #}
    
  3. Form Handling: Use FormExtension for Twig forms (if using Symfony Forms):

    {{ form_start(form) }}
      {{ form_widget(form.username) }}
      {{ form_errors(form) }}
    {{ form_end(form) }}
    
  4. Integration with Laravel:

    • Twig in Laravel: Use twig-laravel/twig to bridge Twig with Laravel’s templating.
    • Service Binding: Bind Twig’s environment to Laravel’s container:
      $this->app->singleton(Twig_Environment::class, function ($app) {
          $loader = new \Twig\Loader\FilesystemLoader($app['path.base'].'/resources/views');
          return new Twig_Environment($loader, [
              'cache' => $app['path.cache'].'/twig',
              'debug' => $app->environment() === 'local',
          ]);
      });
      
    • Passing Data: Share Laravel data (e.g., auth user) via Twig globals:
      $twig->addGlobal('auth', $app['auth']->user());
      
  5. Custom Extensions: Extend Twig’s functionality by creating custom extensions:

    // app/Extensions/CustomExtension.php
    class CustomExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new \Twig\TwigFunction('greet', [$this, 'greetUser']),
            ];
        }
    
        public function greetUser($name)
        {
            return "Hello, $name!";
        }
    }
    

    Register in config/packages/twig.yaml:

    twig:
        extensions:
            - App\Extensions\CustomExtension
    

Gotchas and Tips

Pitfalls

  1. Caching Issues:

    • Clear Twig cache after adding new extensions:
      php bin/console cache:clear
      
    • Debug mode (debug: true in twig.yaml) bypasses caching but slows development.
  2. Namespace Conflicts:

    • Avoid naming custom extensions/functions the same as built-in ones (e.g., upper).
    • Prefix custom functions (e.g., app_greet).
  3. Symfony vs. Laravel Quirks:

    • Route Names: Laravel’s route names differ from Symfony’s. Use path() with Laravel’s route names:
      {{ path('home') }}  {# Laravel route #}
      
    • Asset Paths: Use Laravel’s asset() helper in Twig:
      <img src="{{ asset('images/logo.png') }}">
      
  4. Deprecation Warnings:

    • twig/extra-bundle is a wrapper for twig/extra. Ensure compatibility with your Twig version (e.g., Twig 3.x for Symfony 5.4+).

Debugging Tips

  1. Enable Twig Debugging:

    twig:
        debug: true
        strict_variables: true  {# Catch undefined variables #}
    

    View errors in browser or Symfony’s profiler.

  2. Log Twig Output: Use Symfony’s logger to dump Twig variables:

    {{ dump(_context) }}  {# Symfony-only; use `var_dump()` in Laravel #}
    
  3. Extension Loading Order: Extensions are loaded in alphabetical order. Explicitly order them in twig.yaml if dependencies exist:

    twig:
        extensions:
            - App\Extensions\FirstExtension
            - App\Extensions\SecondExtension
    

Extension Points

  1. Override Built-in Extensions: Disable default extensions and provide custom ones:

    twig:
        extra_bundle:
            enabled: false
    

    Then register only the extensions you need:

    twig:
        extensions:
            - Twig\Extensions\StringExtension
            - App\Extensions\CustomExtension
    
  2. Add Custom Filters/Functions: Extend existing extensions without rewriting them:

    class ExtendedStringExtension extends \Twig\Extensions\StringExtension
    {
        public function getFilters()
        {
            return array_merge(
                parent::getFilters(),
                [
                    new \Twig\TwigFilter('custom_upper', [$this, 'customUpper']),
                ]
            );
        }
    
        public function customUpper($string)
        {
            return strtoupper($string) . " (custom)";
        }
    }
    
  3. Leverage Symfony’s Event System: Hook into Twig events (e.g., Twig\EventDispatcher\EnvironmentEvents::PRE_RENDER) to modify output dynamically.

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