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

bengor-user/twig-bridge

TwigBridge is an adapter that makes BenGorUser “User” objects compatible with Twig templates. Install via Composer and use it to expose user data cleanly in Twig-based views. Requires PHP 5.5+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require bengor-user/twig-bridge
    

    Ensure your Laravel project uses the bengor-user/user package (this bridge is an adapter for it).

  2. Register the Bridge In your config/app.php, add the bridge to the aliases array under the Twig namespace:

    'aliases' => [
        // ...
        'TwigBridge' => BenGorUser\TwigBridge\TwigBridge::class,
    ],
    
  3. Configure Twig In your config/twig.php, register the bridge as a Twig extension:

    'extensions' => [
        // ...
        BenGorUser\TwigBridge\TwigBridge::class,
    ],
    
  4. First Use Case Pass a BenGorUser\User object to Twig and access its properties directly:

    {{ user.getFullName() }}  {# Outputs the user's full name #}
    {{ user.getEmail() }}     {# Outputs the user's email #}
    

Implementation Patterns

Workflow: Integrating with Laravel + Twig

  1. User Model Integration Extend Laravel’s Authenticatable with BenGorUser\User:

    use BenGorUser\User;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class UserModel extends Authenticatable implements User
    {
        use Notifiable;
        // Implement BenGorUser\User methods (e.g., getFullName(), getEmail())
    }
    
  2. Passing Users to Views In your controller, pass the authenticated user to Twig:

    public function showProfile()
    {
        return view('profile', [
            'user' => auth()->user(), // UserModel instance
        ]);
    }
    
  3. Twig Filters/Functions Leverage TwigBridge to expose custom methods:

    {# Display user's role #}
    {{ user.getRole() }}
    
    {# Check if user is active #}
    {% if user.isActive() %}
        <p>Active User</p>
    {% endif %}
    
  4. Dynamic Property Access Use Twig’s attribute function for dynamic properties:

    {{ attribute(user, 'getAvatarUrl') }}
    

Best Practices

  • Type Safety: Ensure your UserModel implements all required BenGorUser\User methods.
  • Caching: Cache Twig templates if users are frequently rendered (e.g., {{ user|cache(3600) }}).
  • Fallbacks: Handle missing methods gracefully in Twig:
    {{ user.getBio()|default('No bio available') }}
    

Gotchas and Tips

Pitfalls

  1. Outdated Package

    • Last release was in 2017. Test thoroughly with your Laravel/Twig versions (PHP ≥5.5).
    • Mitigation: Fork the repo and update dependencies (e.g., Twig ≥2.x) if needed.
  2. Method Name Mismatches

    • TwigBridge assumes BenGorUser\User methods are prefixed with get (e.g., getEmail()).
    • Fix: Override TwigBridge’s getMethods() in a custom extension:
      class CustomTwigBridge extends \BenGorUser\TwigBridge\TwigBridge
      {
          protected function getMethods()
          {
              return ['email', 'fullName']; // Maps to getEmail(), getFullName()
          }
      }
      
  3. Namespace Collisions

    • If using multiple Twig extensions, ensure TwigBridge is loaded after other extensions.
  4. Authentication Context

    • TwigBridge doesn’t handle Laravel’s auth() helper. Pass the user explicitly:
      {% if user %}
          {{ user.getName() }}
      {% endif %}
      

Debugging Tips

  • Check Registered Methods: Dump the available methods in Twig:
    {{ dump(user) }} {# Inspect object structure #}
    
  • Enable Twig Debug: In config/twig.php, set:
    'debug' => env('APP_DEBUG', false),
    
  • Log Missing Methods: Extend TwigBridge to log undefined methods:
    public function __call($method, $args)
    {
        if (!method_exists($this->user, $method)) {
            Log::warning("Method {$method} not found on user");
        }
        return parent::__call($method, $args);
    }
    

Extension Points

  1. Custom User Classes Override TwigBridge to support non-BenGorUser\User objects:

    class CustomUserBridge extends TwigBridge
    {
        public function __construct($user, array $methods = [])
        {
            $this->user = $user;
            $this->methods = $methods; // Define allowed methods
        }
    }
    
  2. Add Twig Tests Test your custom bridge with PHPSpec:

    vendor/bin/phpspec run -fpretty spec/BenGorUser/TwigBridge/CustomTwigBridgeSpec
    
  3. Performance Optimization Cache the getMethods() result if the user object is immutable:

    private $methodsCache;
    
    protected function getMethods()
    {
        if (!$this->methodsCache) {
            $this->methodsCache = parent::getMethods();
        }
        return $this->methodsCache;
    }
    

Laravel-Specific Quirks

  • Service Provider Binding: Bind the bridge in a service provider for DI:
    $this->app->bind('twig.bridge', function ($app) {
        return new CustomTwigBridge(auth()->user());
    });
    
  • Blade + Twig Hybrid: Use BladeOne to embed Twig templates, but ensure the user object is passed correctly:
    BladeOne::addNamespace('twig', resource_path('views/twig'));
    return BladeOne::render('twig/profile.twig', ['user' => auth()->user()]);
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime