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 Hooks Laravel Package

sylius/twig-hooks

Sylius Twig Hooks is a lightweight component from the Sylius Stack initiative that adds a hook-based extension system for Twig templates, making it easier to customize and extend views in a structured, decoupled way.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Modularity & Composability: The package enables Twig template modularity via hooks, aligning well with component-based architectures (e.g., micro-frontends, headless CMS, or modular monoliths). Ideal for projects requiring dynamic layout injection (e.g., e-commerce, SaaS dashboards) without deep template refactoring.
  • Separation of Concerns: Decouples layout structure from content logic, reducing template spaghetti. Fits PHP/Laravel projects where Twig is used for server-side rendering (SSR) or hybrid rendering (e.g., Inertia.js + Twig).
  • Sylius Ecosystem: Primarily designed for Sylius (e-commerce), but generic enough for any Laravel app needing flexible Twig layouts. Risk of over-engineering for simple projects.

Integration Feasibility

  • Laravel Compatibility:
    • Works with Laravel’s Twig integration (via laravel/tinker or spatie/laravel-twig).
    • No native Laravel service provider (unlike Sylius), so manual bootstrapping is required.
    • Hook registration must be explicit (e.g., via service container or middleware).
  • Twig Version: Requires Twig 2.x+ (Laravel 9+ uses Twig 2.15+ by default).
  • Dependency Overhead: Lightweight (~100 LOC), but adds runtime reflection for hook resolution (minimal performance impact).

Technical Risk

  • Hook Naming Collisions: Poorly named hooks (e.g., header vs. site_header) can lead to unintended overrides.
  • Debugging Complexity: Hooks introduce indirection; debugging layout issues requires tracing the hook call stack.
  • State Management: Hooks are stateless by design; complex stateful layouts may need session/dependency injection workarounds.
  • Testing: Requires mocking Twig environment in PHPUnit (e.g., Twig_Test_Environment).

Key Questions

  1. Use Case Justification:
    • Is dynamic layout injection a core requirement, or can this be achieved via Twig extends/blocks or Laravel Blade components?
    • Would Alpine.js/Vue (client-side) or Laravel Livewire (server-side) be a better fit for interactivity?
  2. Performance:
    • How many hooks will be active per request? (High cardinality could impact Twig compilation.)
  3. Team Familiarity:
    • Does the team have experience with hook-based systems (e.g., WordPress filters/actions)?
  4. Alternatives:
    • Compare with:
      • Laravel Blade @stack/@push (simpler, built-in).
      • Twig Extensions (for custom logic).
      • Headless CMS (e.g., Strapi, Contentful) for layout management.

Integration Approach

Stack Fit

  • Best Fit:
    • Laravel + Twig projects needing runtime layout customization (e.g., A/B testing, feature flags, or modular themes).
    • Sylius-based or e-commerce apps where product-specific layouts are common.
  • Partial Fit:
    • Projects using Blade templates (can emulate hooks with Blade directives but loses Twig’s flexibility).
    • API-first Laravel apps (if using Twig for SSR, e.g., with Inertia).
  • Poor Fit:
    • Pure Blade projects (no Twig).
    • Static site generators (e.g., Laravel Vapor + Tailwind).

Migration Path

  1. Assessment Phase:
    • Audit existing Twig templates for reusable components (e.g., headers, footers).
    • Identify pain points (e.g., duplicate code, hardcoded sections).
  2. Proof of Concept:
    • Implement 1–2 hooks (e.g., before_content, after_sidebar) in a non-critical template.
    • Test with different themes or user roles to validate isolation.
  3. Incremental Rollout:
    • Phase 1: Replace static includes (e.g., {% include 'partials/header.html.twig' %}) with hooks.
    • Phase 2: Migrate conditional logic (e.g., {% if user.is_admin %}...{% endif %}) to hook-based registration.
    • Phase 3: Integrate with Laravel events or middleware for dynamic hook injection.
  4. Tooling:
    • Use Twig’s {% debug %} to inspect hook context.
    • Add custom Twig extensions for hook utilities (e.g., {{ hook_exists('footer') }}).

Compatibility

  • Laravel Versions:
    • Tested with Laravel 9+ (Twig 2.x). For Laravel 8, use twig/twig:v2.12.
    • Composer: require sylius/twig-hooks:^1.0.
  • Twig Extensions:
    • Ensure no conflicts with existing extensions (e.g., Twig\Extension\AbstractExtension).
  • Caching:
    • Hooks bypass Twig’s cache by default (runtime resolution). For production, configure:
      $twig->addExtension(new \Sylius\TwigHooks\TwigHooksExtension());
      $twig->setCache(false); // Disable if using hooks dynamically
      

Sequencing

  1. Prerequisites:
    • Laravel project with Twig installed (spatie/laravel-twig or manual setup).
    • Template structure defined (e.g., base.html.twig with hook placeholders).
  2. Core Integration:
    • Register hooks in AppServiceProvider:
      public function boot(): void {
          $twig = $this->app['twig'];
          $twig->addExtension(new \Sylius\TwigHooks\TwigHooksExtension());
      }
      
    • Define hook placeholders in Twig:
      {# base.html.twig #}
      <body>
          {% hook 'header' %}
          {% hook 'content' %}
          {% hook 'footer' %}
      </body>
      
  3. Dynamic Hooks:
    • Implement hook providers (e.g., middleware, services):
      $twigHooks->addHook('header', new \Twig\Markup('<nav>Dynamic Header</nav>', 'UTF-8'));
      
  4. Testing:
    • Write hook-specific tests (mock TwigHooksExtension).
    • Test edge cases (empty hooks, nested hooks, priority conflicts).

Operational Impact

Maintenance

  • Pros:
    • Reduces template duplication (DRY principle).
    • Centralized hook management (e.g., via config or database).
  • Cons:
    • Hook sprawl: Unused hooks accumulate over time (enforce naming conventions and deprecation).
    • Dependency on Twig: Breaking changes in Twig (e.g., v3.0) may require updates.
  • Best Practices:
    • Document hooks in a HOOKS.md file (name, purpose, examples).
    • Version hooks (e.g., header_v2) for backward compatibility.
    • Use Laravel tags to group hooks by feature/module.

Support

  • Debugging:
    • Hook resolution order can be opaque. Log hook calls:
      \Sylius\TwigHooks\TwigHooksExtension::enableDebugMode();
      
    • Twig profiler (twig/extra-bundle) to inspect hook execution.
  • Common Issues:
    • Missing hooks: Add a fallback template or linter to detect unused hooks.
    • Performance: Profile with Xdebug if hooks slow down rendering.
  • Support Tools:
    • Laravel Telescope to track hook registration events.
    • Custom CLI commands to list active hooks:
      php artisan twig:hooks:list
      

Scaling

  • Performance:
    • Hook resolution is O(n) per template. Mitigate with:
      • Lazy-loading hooks (e.g., only load footer hook if {% hook 'footer' %} exists).
      • Caching hook results (if hooks are static):
        $hookCache = new \Symfony\Component\Cache\Adapter\ArrayAdapter();
        $twigHooks->setCache($hookCache);
        
    • Benchmark with 100+ hooks to validate scalability.
  • Horizontal Scaling:
    • Stateless hooks work well in queued jobs or serverless (e.g., Laravel Vapor).
    • Stateful hooks (e.g
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle