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 Extra Bundle Laravel Package

csanquer/twig-extra-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require csanquer/twig-extra-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Csanquer\TwigExtraBundle\CsanquerTwigExtraBundle::class => ['all' => true],
    ];
    
  2. First Use Case Use the asset_manager Twig function to concatenate and render JS assets in a base layout:

    {% block javascripts %}
        {{ asset_manager([
            '@YourBundle/Resources/public/js/app.js',
            '@YourBundle/Resources/public/js/vendor.js'
        ]) }}
    {% endblock %}
    

    This outputs a single <script> tag with concatenated content in the order provided.


Implementation Patterns

Common Workflows

  1. Asset Concatenation in Layouts

    • Place the asset_manager call in a base template (e.g., base.html.twig) to ensure all JS assets are rendered once.
    • Example:
      {% block javascripts %}
          {{ asset_manager([
              'bundles/yourbundle/js/main.js',
              'https://cdn.example.com/library.js'
          ]) }}
      {% endblock %}
      
  2. Conditional Asset Loading

    • Use Twig’s if logic to load assets dynamically:
      {% if app.user.isAdmin %}
          {{ asset_manager(['@YourBundle/Resources/public/js/admin.js']) }}
      {% endif %}
      
  3. Integration with Webpack Encore

    • If using Encore, manually concatenate assets in Twig after Webpack’s output to avoid duplication:
      {{ encore_entry_link_tags('app') }}
      {{ asset_manager(['@YourBundle/Resources/public/js/extra.js']) }}
      
  4. Asset Grouping by Route

    • Create a Twig extension to group assets by route (e.g., admin or frontend):
      {% set adminAssets = ['@YourBundle/Resources/public/js/admin/*.js'] %}
      {{ asset_manager(adminAssets) }}
      

Integration Tips

  • Symfony Asset Component: Combine with asset() for local files and asset_manager for concatenation.
  • Cache Control: Leverage Symfony’s HTTP cache headers (e.g., Etag) to cache concatenated assets.
  • Debug Mode: Disable concatenation in dev environments for easier debugging:
    {% if app.environment == 'dev' %}
        {% for asset in assets %}
            <script src="{{ asset(asset) }}"></script>
        {% endfor %}
    {% else %}
        {{ asset_manager(assets) }}
    {% endif %}
    

Gotchas and Tips

Pitfalls

  1. Asset Path Resolution

    • Issue: Relative paths (e.g., js/app.js) may fail if not rooted in public/.
    • Fix: Use absolute paths (e.g., @YourBundle/Resources/public/js/app.js) or configure Twig’s paths in config/packages/twig.yaml.
  2. External CDN Assets

    • Issue: asset_manager may not handle CDN URLs (e.g., https://...) optimally, as they bypass Symfony’s asset pipeline.
    • Fix: Exclude CDN assets from concatenation or use a separate <script> tag.
  3. Caching Headaches

    • Issue: Concatenated assets may not invalidate properly if individual files change.
    • Fix: Append a query string (e.g., ?v={{ filemtime('path/to/file.js') }}) or use Symfony’s AssetVersionStrategy.
  4. Twig Extension Conflicts

    • Issue: Naming conflicts with other Twig extensions (e.g., asset() from Symfony\Bridge\Twig\Extension\AssetExtension).
    • Fix: Prefix the function call (e.g., {{ csanquer_asset_manager(...) }}) by overriding the Twig environment.

Debugging

  • Check Output: Inspect the rendered HTML to verify concatenation:
    php bin/console debug:twig | grep asset_manager
    
  • Log Asset Paths: Temporarily log paths in a Twig extension to debug resolution:
    // In a custom Twig extension
    public function getAssetPaths($assets) {
        \Log::debug('Asset paths:', $assets);
        return $assets;
    }
    

Extension Points

  1. Custom Asset Filters

    • Extend the bundle by creating a custom Twig filter to preprocess assets (e.g., minification):
      // src/Twig/AppExtension.php
      public function getFilters() {
          return [
              new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
          ];
      }
      
      {{ asset_manager(assets | map('minify_js')) }}
      
  2. Override AssetManager

    • Replace the default AssetManager service to add logic (e.g., versioning):
      # config/services.yaml
      Csanquer\TwigExtraBundle\Twig\AssetManager:
          arguments:
              $version: '%kernel.cache_dir%/assets/version.txt'
      
  3. Add Asset Types

    • Extend the bundle to support CSS or other asset types by modifying the AssetManager class:
      // Override Csanquer\TwigExtraBundle\Twig\AssetManager
      public function renderAssets(array $assets) {
          foreach ($assets as $asset) {
              if (strpos($asset, '.css') !== false) {
                  // Custom CSS logic
              }
          }
      }
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle