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

bengor-user/twig-bridge-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the Bundle**
   ```bash
   composer require bengor-user/twig-bridge-bundle

Ensure your composer.json includes symfony/twig-bundle and bengor-user/user-bundle as dependencies.

  1. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        BenGorUser\TwigBridgeBundle\BenGorUserTwigBridgeBundle::class => ['all' => true],
    ];
    
  2. First Use Case: User Data in Twig Inject the UserBundle's user object into Twig templates by extending your base template:

    {% extends 'base.html.twig' %}
    
    {% block user_info %}
        {{ app.user.username }}  {# Access user properties directly #}
        {{ app.user.getFullName() }}  {# Call methods if available #}
    {% endblock %}
    
  3. Verify Configuration Check config/packages/twig.yaml for Twig extensions and ensure UserBundle's services are autowired.


Implementation Patterns

Core Workflow: Templating with User Data

  1. Accessing User Data

    • Use app.user in Twig templates to access the authenticated user object.
    • Example:
      {% if app.user.isAuthenticated %}
          <p>Welcome, {{ app.user.email }}!</p>
      {% endif %}
      
  2. Custom User Properties

    • Extend the User entity (from UserBundle) with getters/setters for custom fields.
    • Example:
      // src/Entity/User.php
      public function getFullName(): string
      {
          return $this->firstName . ' ' . $this->lastName;
      }
      
    • Access in Twig:
      {{ app.user.getFullName() }}
      
  3. Conditional Logic

    • Use Twig’s if statements to handle guest vs. authenticated users:
      {% if app.user.isAuthenticated %}
          {{ include('user_dashboard.html.twig') }}
      {% else %}
          {{ include('login_prompt.html.twig') }}
      {% endif %}
      
  4. Integration with Forms

    • Pre-fill forms with user data:
      {{ form_start(form) }}
          {{ form_row(form.email, {'value': app.user.email}) }}
      {{ form_end(form) }}
      
  5. Global Variables

    • Override Twig’s global variables in config/packages/twig.yaml:
      twig:
          globals:
              app_user: '@security.token_storage'
      
    • Access via app_user.getToken().getUser().

Advanced Patterns

  1. Custom Twig Filters/Functions

    • Create a custom Twig extension to add user-specific logic:
      // src/Twig/AppExtension.php
      class AppExtension extends \Twig_Extension
      {
          public function getFunctions()
          {
              return [
                  new \Twig_SimpleFunction('isAdmin', [$this, 'checkAdmin']),
              ];
          }
      
          public function checkAdmin($user)
          {
              return $user->hasRole('ROLE_ADMIN');
          }
      }
      
    • Register the extension in services.yaml:
      services:
          App\Twig\AppExtension:
              tags: ['twig.extension']
      
    • Use in Twig:
      {% if isAdmin(app.user) %}
          <p>Admin Panel</p>
      {% endif %}
      
  2. Event Listeners for User Data

    • Listen to security.interactive_login to update Twig globals dynamically:
      // src/EventListener/UserListener.php
      class UserListener
      {
          public function onLogin(GetResponseUserEvent $event)
          {
              $user = $event->getUser();
              // Update Twig globals or cache user data
          }
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\UserListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'security.interactive_login' }
      
  3. Caching User Data

    • Cache frequently accessed user data (e.g., roles) to improve performance:
      // src/Service/UserCache.php
      class UserCache
      {
          public function getCachedRoles(UserInterface $user): array
          {
              return $this->cache->get('user_roles_' . $user->getId(), function() use ($user) {
                  return $user->getRoles();
              });
          }
      }
      
    • Use in Twig via a custom extension.

Gotchas and Tips

Common Pitfalls

  1. Outdated Dependencies

    • The bundle was last updated in 2017 and requires Symfony 2.8+. Ensure compatibility with your Symfony version (e.g., test with Symfony 4/5 if possible).
    • Workaround: Fork the repository and update dependencies manually if needed.
  2. Missing UserBundle

    • The bundle requires bengor-user/user-bundle. Install it first:
      composer require bengor-user/user-bundle
      
    • Error: Class 'BenGorUser\UserBundle\UserBundle' not found → Install the missing bundle.
  3. Twig Global Overrides

    • If app.user is undefined, verify:
      • The UserBundle is enabled in bundles.php.
      • The TwigBridgeBundle is loaded after UserBundle and TwigBundle.
      • The security.token_storage service is properly injected.
  4. Circular Dependencies

    • Avoid circular references between UserBundle, TwigBridgeBundle, and custom extensions. Use lazy-loading or interfaces to decouple components.
  5. Deprecated Symfony Features

    • The bundle uses older Symfony patterns (e.g., Twig_Extension instead of Twig\Extension). Update to modern equivalents if migrating to Symfony 5+:
      // Old
      class OldExtension extends \Twig_Extension
      // New
      class NewExtension extends AbstractExtension
      

Debugging Tips

  1. Check Service Availability

    • Dump the security.token_storage service to verify the user object:
      bin/console debug:container security.token_storage
      
    • Look for user property in the output.
  2. Twig Debugging

    • Enable Twig debugging in config/packages/dev/twig.yaml:
      twig:
          debug: true
          strict_variables: true
      
    • Use {{ dump(app.user) }} in templates to inspect the user object.
  3. Event Debugging

    • Listen to Twig events to debug template rendering:
      // src/EventListener/DebugListener.php
      class DebugListener
      {
          public function onKernelRequest(GetResponseEvent $event)
          {
              if ($event->isMasterRequest()) {
                  $this->container->get('twig')->addGlobal('debug_user', $this->container->get('security.token_storage')->getToken()->getUser());
              }
          }
      }
      

Extension Points

  1. Custom User Data

    • Extend the User entity to add domain-specific properties/methods:
      // src/Entity/User.php
      public function getProfilePictureUrl(): string
      {
          return '/uploads/' . $this->id . '.jpg';
      }
      
    • Access in Twig:
      <img src="{{ app.user.getProfilePictureUrl() }}" alt="Profile">
      
  2. Override Twig Globals

    • Replace the default app.user global with a custom service:
      # config/packages/twig.yaml
      twig:
          globals:
              app_user: '@app.custom_user_service'
      
    • Create a service that wraps the user object:
      // src/Service/CustomUserService.php
      class CustomUserService
      {
          public function __construct(private UserInterface $user) {}
      
          public function getUser(): UserInterface
          {
              return $this->user;
          }
      }
      
  3. Add Twig Filters

    • Create filters for user-specific operations (e.g., formatting usernames):
      // src/Twig/UserFilter.php
      class UserFilter extends AbstractExtension
      {
          public function getFilters()
          {
              return [
                  new FilterMethod($this, 'formatUsername', ['is_safe' => ['html']]),
              ];
          }
      
          public function formatUsername($username): string
          {
              return ucfirst(strtolower($username));
          }
      }
      
    • Use in Twig:
      {{ app.user.username|formatUsername }}
      
  4. Integration with API Platform

    • If using api-platform, expose user data via serializers:
      // src/Serializer/UserNormalizer.php
      class UserNormalizer implements NormalizerInterface
      {
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle