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

Underscore Bundle Laravel Package

bmatzner/underscore-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require bmatzner/underscore-bundle:~1.8
    

    Update AppKernel.php to include the bundle:

    new Bmatzner\UnderscoreBundle\BmatznerUnderscoreBundle(),
    
  2. Asset Installation:

    php app/console assets:install web --symlink
    
  3. First Use Case: Include the library in a Twig template:

    <script src="{{ asset('bundles/bmatznerunderscore/js/underscore.min.js') }}"></script>
    

    Use Underscore.js in a frontend script:

    <script>
        _.each([1, 2, 3], function(num) { console.log(num); });
    </script>
    

Where to Look First

  • Documentation: Underscore.js Official Docs (primary reference).
  • Bundle Structure: vendor/bmatzner/underscore-bundle/ for source files.
  • Symfony Asset Management: app/console assets:install for asset handling.

Implementation Patterns

Common Workflows

  1. Frontend Utility Library: Use Underscore.js for client-side data manipulation (e.g., filtering, mapping, templating). Example:

    // Filter an array of objects
    var filtered = _.filter(users, { age: 25 });
    
  2. Twig Integration: Pass data from PHP to Twig, then process it with Underscore in the browser:

    <script>
        var userData = {{ users|json_encode|raw }};
        var activeUsers = _.filter(userData, { active: true });
    </script>
    
  3. Custom Templates: Use Underscore’s templating engine for dynamic HTML:

    var template = _.template('<%= name %> is <%= age %> years old.');
    template({ name: 'Alice', age: 30 });
    
  4. Event Delegation: Leverage Underscore for lightweight event handling:

    _.extend($, {
        delegate: function(selector, event, handler) {
            $(document).on(event, selector, handler);
        }
    });
    

Integration Tips

  • Asset Optimization: Combine underscore.min.js with other JS files using Symfony’s assetic or webpack-encore. Example webpack.config.js:

    Encore
        .addEntry('app', './assets/app.js')
        .addEntry('underscore', 'bmatzner/underscore-bundle/js/underscore.min.js')
        .splitEntry('underscore');
    
  • Versioning: Pin the bundle version in composer.json to avoid breaking changes:

    "bmatzner/underscore-bundle": "1.8.0"
    
  • Testing: Use Jasmine or Mocha with Underscore for frontend unit tests.


Gotchas and Tips

Pitfalls

  1. Asset Paths:

    • Hardcoding paths like bundles/bmatznerunderscore/js/underscore.min.js may break if the bundle is renamed or moved.
    • Fix: Always use {{ asset() }} in Twig.
  2. Bundle Deprecation:

    • The bundle is archived and may not receive updates. Underscore.js itself is also in maintenance mode.
    • Mitigation: Consider alternatives like Lodash (a modern fork of Underscore) or self-hosting the library.
  3. Symfony 4+ Compatibility:

    • This bundle is designed for Symfony 2/3. For Symfony 4+, use a standalone asset installation:
      npm install underscore --save
      
      Then import in webpack.config.js:
      Encore.enableSingleRuntimeChunk();
      Encore.addEntry('underscore', 'underscore');
      
  4. License Conflicts:

    • Underscore.js is licensed under MIT, but ensure compatibility with your project’s license (e.g., GPL).

Debugging

  • Missing Library: Verify assets are installed (web/bundles/bmatznerunderscore/js/underscore.min.js exists). Clear cache if needed:

    php app/console cache:clear
    
  • Underscore Undefined: Check for JavaScript errors (e.g., ReferenceError: _ is not defined). Ensure the script tag loads after DOM ready:

    <script src="{{ asset('bundles/bmatznerunderscore/js/underscore.min.js') }}"></script>
    <script src="{{ asset('js/app.js') }}"></script>
    

Extension Points

  1. Custom Builds: Override the default underscore.min.js by copying the file to your project’s web/bundles/ and modifying it.

  2. Symfony Integration: Create a Twig extension to expose Underscore utilities to templates:

    // src/Twig/UnderscoreExtension.php
    class UnderscoreExtension extends \Twig_Extension
    {
        public function getFunctions()
        {
            return [
                new \Twig_SimpleFunction('underscore_filter', function($array, $predicate) {
                    return json_encode(_.filter($array, $predicate));
                }),
            ];
        }
    }
    

    Usage in Twig:

    {{ underscore_filter(users, { active: true })|raw }}
    
  3. Lodash Migration: Replace Underscore with Lodash by:

    • Removing the bundle.
    • Installing Lodash via npm:
      npm install lodash --save
      
    • Updating imports in your JS files.

Performance Tips

  • Lazy Loading: Load Underscore asynchronously if not needed immediately:

    <script src="{{ asset('bundles/bmatznerunderscore/js/underscore.min.js') }}" defer></script>
    
  • Tree Shaking: If using Webpack, configure it to exclude unused Underscore methods:

    Encore.configureBabel((config) => {
        config.plugins.push('@babel/plugin-transform-runtime');
    });
    
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