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

Twig Extensions Bundle Laravel Package

brazilianfriendsofsymfony/twig-extensions-bundle

Symfony bundle adding Twig filters (format bytes, left/right alignment) and form types, including a CKEditor-based rich textarea and an FCBKComplete entity autocomplete widget. Includes Twig form theme integration and basic setup instructions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require brazilianfriendsofsymfony/twig-extensions-bundle
    

    (Note: The original README uses a legacy Git submodule approach; Composer is preferred in modern Laravel/Symfony.)

  2. Enable the Bundle: Add to config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):

    return [
        // ...
        BFOS\TwigExtensionsBundle\BFOSTwigExtensionsBundle::class => ['all' => true],
    ];
    
  3. Configure Twig: Add to config/packages/twig.yaml:

    twig:
        form_themes:
            - '@BFOSTwigExtensions/form_div_layout.html.twig'
    
  4. First Use Case: Use the bfos_format_bytes filter in a Twig template:

    {{ 1024 | bfos_format_bytes }}  {# Outputs: 1.0 kB #}
    

Implementation Patterns

Twig Filters

  • Human-Readable Bytes:

    {# SI (default) #}
    {{ disk_size | bfos_format_bytes }}
    
    {# Binary #}
    {{ disk_size | bfos_format_bytes(false) }}
    

    Use case: Displaying file sizes in admin panels or user dashboards.

  • Text Alignment:

    {# Right-align in 20-character width #}
    {{ "Hello" | bfos_align_right(20) }}
    
    {# Left-align in 15-character width #}
    {{ "World" | bfos_align_left(15) }}
    

    Use case: Generating pre-formatted tables or logs with consistent column widths.

Form Types

  • Rich Textarea (CKEditor):

    $builder->add('description', 'bfos_richtextarea', [
        'config' => [
            'toolbar' => ['Basic', 'Document', 'Clipboard', 'Editing', 'Forms'],
        ],
    ]);
    

    Use case: Replacing textarea with a WYSIWYG editor in content-heavy forms.

  • Date/DateTime Pickers:

    $builder->add('event_date', 'bfos_datetime', [
        'widget' => 'single_text', // Avoid if using this option (per README)
        'attr' => ['class' => 'datepicker'],
    ]);
    

    Use case: Calendar-based input fields (e.g., event scheduling).

  • FCBKComplete Entity (Autocomplete):

    $builder->add('users', 'bfos_fcbkcomplete_entity', [
        'class' => App\Entity\User::class,
        'url' => $this->generateUrl('user_autocomplete'),
        'fcbkcomplete_options' => ['minInputLength' => 2],
    ]);
    

    Use case: Search-as-you-type user/role selection (requires a custom route/controller).

Integration Tips

  1. Laravel-Symfony Bridge: Use spatie/symfony or laravel/symfony-bundle to integrate Symfony bundles into Laravel. Example:

    composer require spatie/symfony
    
  2. Customize CKEditor Config: Override the default config via Twig:

    {% block bfos_richtextarea_config %}
        {
            "toolbar": ["Bold", "Italic", "NumberedList"],
            "extraPlugins": "justify"
        }
    {% endblock %}
    
  3. Dynamic Filter Usage: Create a Twig extension to wrap filters for reusable logic:

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new \Twig\TwigFunction('format_bytes', [$this, 'formatBytes']),
            ];
        }
    
        public function formatBytes($bytes, $binary = true)
        {
            return (new \BFOS\TwigExtensionsBundle\Twig\BytesExtension())->formatBytes($bytes, $binary);
        }
    }
    

    Usage:

    {{ format_bytes(disk_usage) }}
    

Gotchas and Tips

Pitfalls

  1. Deprecated Workflow:

    • The bundle assumes Symfony’s legacy deps system. Use Composer for modern projects.
    • Fix: Ignore the deps section in the README and rely on Composer.
  2. Form Widget Conflicts:

    • The bfos_datetime and bfos_date types do not support widget: single_text (per README).
    • Fix: Use widget: single_text only with standard Symfony form types.
  3. FCBKComplete Dependencies:

    • Requires jQuery UI for autocomplete styling.
    • Fix: Include in your assets:
      <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      
  4. CKEditor Assets:

    • The bfos_richtextarea relies on CKEditor 4 (outdated).
    • Fix: Override the asset path in config:
      bfos_twig_extensions:
          ckeditor_path: '/vendor/ckeditor/ckeditor4/'
      

Debugging

  • Filter Not Found: Ensure the bundle is enabled and Twig is configured to load its resources. Debug: Check config/packages/twig.yaml for form_themes.

  • Autocomplete Fails: Verify the route/controller returns valid JSON:

    [{"key": "1", "value": "User 1 (user@example.com)"}]
    

    Debug: Use Postman to test the autocomplete endpoint.

  • CKEditor Not Loading: Clear cache and check the browser console for 404 errors on CKEditor JS/CSS. Debug: Override the asset path as shown above.

Extension Points

  1. Custom Filters: Extend the bundle by creating a new Twig extension:

    // src/Twig/CustomExtension.php
    class CustomExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFilters()
        {
            return [
                new \Twig\TwigFilter('custom_align', [$this, 'customAlign']),
            ];
        }
    
        public function customAlign($str, $width = 10, $align = 'left')
        {
            return (new \BFOS\TwigExtensionsBundle\Twig\AlignmentExtension())->align($str, $width, $align);
        }
    }
    
  2. Override Form Themes: Copy vendor/bfos/twig-extensions-bundle/Resources/views/Form/form_div_layout.html.twig to templates/BFOSTwigExtensions/form_div_layout.html.twig and customize.

  3. Binary vs. SI Units: The bfos_format_bytes filter defaults to SI units (kB, MB). Force binary (KiB, MiB) with false:

    {{ disk_size | bfos_format_bytes(false) }}
    

Performance Tips

  • Lazy-Load Filters: For large datasets, cache formatted bytes:

    {% cache app.format_bytes %}
        {{ sizes | map((item) => item | bfos_format_bytes) }}
    {% endcache %}
    
  • Minify CKEditor: Use a minified version of CKEditor to reduce payload size:

    bfos_twig_extensions:
        ckeditor_path: '/vendor/ckeditor/ckeditor4/ckeditor.js'  # Point to minified file
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours