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

Marionette Bundle Laravel Package

bmatzner/marionette-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies: Run composer require bmatzner/marionette-bundle:^1.8 and update bundles in AppKernel.php as shown.
  2. Asset Installation: Execute php app/console assets:install web (or --symlink for development).
  3. Verify Dependencies: Ensure json2, jquery, underscore, and backbone are loaded in your base template:
    {# app/Resources/views/base.html.twig #}
    {% block javascripts %}
        {{ parent() }}
        <script src="{{ asset('bundles/bmatznerjson2/js/json2.min.js') }}"></script>
        <script src="{{ asset('bundles/bmatznerjquery/js/jquery.min.js') }}"></script>
        <script src="{{ asset('bundles/bmatznerunderscore/js/underscore.min.js') }}"></script>
        <script src="{{ asset('bundles/bmatznerbackbone/js/backbone.min.js') }}"></script>
        <script src="{{ asset('bundles/bmatznermarionette/js/marionette.min.js') }}"></script>
    {% endblock %}
    

First Use Case: Basic Marionette App

Create a simple Marionette app in a Twig template:

{# app/Resources/views/hello_marionette.html.twig #}
{% extends 'base.html.twig' %}

{% block body %}
    <div id="app-container"></div>
    <script>
        $(document).ready(function() {
            var App = new Backbone.Marionette.Application();
            App.addRegions({
                mainRegion: "#app-container"
            });

            App.on("initialize:after", function() {
                App.mainRegion.show(new Backbone.Marionette.ItemView({
                    template: "#hello-template"
                }));
            });

            App.start();
        });
    </script>
    <script type="text/template" id="hello-template">
        <h1>Hello, Marionette!</h1>
    </script>
{% endblock %}

Implementation Patterns

1. Asset Management

  • Bundle Structure: Assets are organized under bundles/bmatzner{json2,jquery,underscore,backbone,marionette}/js/.
  • Versioning: Use asset() with versioned URLs (e.g., {{ asset('bundles/bmatznermarionette/js/marionette.min.js?v=1.8.8') }}) to cache-bust.
  • Symlinking: Prefer --symlink in development for live updates:
    php app/console assets:install --symlink web
    

2. Integration with Symfony Controllers

  • Pass Data to Views: Use Symfony’s templating to inject Marionette-ready data:
    // src/AppBundle/Controller/DefaultController.php
    public function indexAction()
    {
        return $this->render('hello_marionette.html.twig', [
            'user' => ['name' => 'John'], // Pass to Twig for JSON serialization
        ]);
    }
    
    {# In Twig #}
    <script>
        var userData = {{ user|json_encode|raw }};
    </script>
    

3. Modular Marionette Apps

  • Region-Based Layouts: Define regions in Twig and bind them to Marionette regions:

    <div id="header-region"></div>
    <div id="content-region"></div>
    <div id="footer-region"></div>
    
    App.addRegions({
        header: "#header-region",
        content: "#content-region",
        footer: "#footer-region"
    });
    
  • Composite Views: Use Backbone.Marionette.Layout for complex UIs:

    var LayoutView = Backbone.Marionette.Layout.extend({
        template: "#layout-template",
        regions: {
            sidebar: "#sidebar-region",
            main: "#main-region"
        }
    });
    

4. API Integration

  • Symfony API ↔ Marionette: Use Symfony’s FOSRestBundle or NelmioApiDocBundle to expose endpoints, then fetch data in Marionette:
    var UserModel = Backbone.Model.extend({
        url: "{{ path('api_user_get') }}",
        parse: function(response) {
            return response.data; // Match Symfony's JSON structure
        }
    });
    

5. Event Handling

  • Cross-Context Events: Trigger events from Symfony (e.g., via WebSocket) and listen in Marionette:
    App.on("user:login", function(user) {
        App.mainRegion.show(new UserDashboardView({ model: user }));
    });
    
    // Symfony event listener (e.g., after login)
    $eventDispatcher->dispatch('user.login', new UserEvent($user));
    

Gotchas and Tips

1. Dependency Conflicts

  • Backbone/Underscore Versions: Marionette 1.8.8 requires Underscore 1.4.4 and Backbone 1.0.0. Check for conflicts with other bundles (e.g., stof/doctrine-extensions might pull newer versions).
    • Fix: Pin versions in composer.json:
      "require": {
          "underscore": "1.4.4",
          "backbone": "1.0.0"
      }
      

2. Asset Loading Order

  • Critical: Marionette depends on jQuery → Underscore → Backbone → Marionette. Load scripts in this order in your base template.
    • Debugging: Check browser console for Uncaught ReferenceError (e.g., Backbone is not defined).

3. Twig Template Caching

  • Marionette Templates: Use type="text/template" for Marionette templates to avoid Twig processing:
    <script type="text/template" id="my-template">
        {{- raw('Hello {{ name }}!') -}} {# Raw to prevent Twig escaping #}
    </script>
    

4. Debugging Marionette

  • Console Logs: Marionette logs to console by default. Enable debug mode in Symfony:
    # app/config/config_dev.yml
    monolog:
        handlers:
            main:
                level: debug
                channels: ["!event"]
    
  • Breakpoints: Use debugger; in Marionette code to pause execution in browser dev tools.

5. Performance Tips

  • Minification: Use --no-dev flag for production assets:
    php app/console assets:install --symlink --no-dev web
    
  • Lazy Loading: Load Marionette only on pages that need it (e.g., via data-marionette attribute and conditional scripts).

6. Extension Points

  • Custom Builds: Override Marionette’s JS by copying files from vendor/bmatzner/marionette-bundle/Resources/public/js/ to web/bundles/marionette/js/ and modify.
  • Symfony Events: Listen to Symfony events (e.g., kernel.request) to initialize Marionette:
    // src/AppBundle/EventListener/MarionetteListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($event->isMasterRequest()) {
            $this->initializeMarionetteApp();
        }
    }
    

7. Common Pitfalls

  • CORS Issues: If fetching data from Symfony API, ensure CORS headers are set:
    # app/config/config.yml
    nelmio_cors:
        defaults:
            allow_origin: ["*"]
            allow_methods: ["GET", "POST", "PUT", "DELETE"]
            allow_headers: ["Content-Type", "Authorization"]
            expose_headers: ["Link"]
    
  • Memory Leaks: Unbind Marionette views/composites when navigating away:
    App.mainRegion.currentView.close(); // Clean up
    App.mainRegion.empty();
    

8. Testing

  • JavaScript Tests: Use Symfony’s panther or laravel-dusk for Marionette integration tests.
  • PHPUnit: Test Symfony-side logic (e.g., API endpoints) that feeds Marionette.
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