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

Symfony Twig Helper Laravel Package

dcylabs/symfony-twig-helper

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dcylabs/symfony-twig-helper dev-master
    

    Add the bundle to config/bundles.php (Laravel 5.5+) or AppKernel.php (older Symfony/Laravel):

    Dcylabs\TwigBundle\DcylabsTwigBundle::class,
    
  2. First Use Case: Use the checkRoles Twig tag in a template to verify if the current user has access to a route/path. Example:

    {% checkRoles '/admin/dashboard' %}
        <div class="access-granted">
            Welcome, Admin! {{ check_url }}
        </div>
    {% else %}
        <div class="access-denied">
            You don't have permission to view this page.
        </div>
    {% endcheckRoles %}
    
  3. Where to Look First:

    • Twig Tags: Focus on checkRoles for role-based path validation.
    • Configuration: Check if the bundle requires any Symfony-specific configurations (e.g., security roles, route matching logic).
    • Documentation: Since the package is minimal, refer to Symfony’s Twig and security bundles for context.

Implementation Patterns

Common Workflows

  1. Role-Based UI Conditionals: Dynamically show/hide UI elements based on path access:

    {% checkRoles '/admin/users', '/admin/settings' %}
        {{ renderAdminPanel() }}
    {% endcheckRoles %}
    
  2. Multi-Path Validation: Validate access to multiple paths at once:

    {% checkRoles '/user/profile', '/user/settings' %}
        <div class="user-actions">
            {{ check_urls | join(', ') }} accessible!
        </div>
    {% endcheckRoles %}
    
  3. Integration with Laravel’s Auth: Since Laravel uses Symfony’s security components, leverage the bundle with Laravel’s Auth::user() and gates/policies:

    {% if app.user and app.user.can('access', '/admin') %}
        {% checkRoles '/admin' %}
            {{ renderAdminContent() }}
        {% endcheckRoles %}
    {% endif %}
    
  4. Custom Logic Extension: Extend the bundle’s behavior by overriding its Twig environment or security logic (see Gotchas for details).

Integration Tips

  • Symfony Security Integration: Ensure your Laravel app’s security layer (e.g., auth.php gates) aligns with the bundle’s path-based checks. Example:

    // app/Providers/AuthServiceProvider.php
    Gate::define('access-path', function ($user, $path) {
        return $user->canAccessPath($path); // Custom logic
    });
    
  • Twig Global Variables: Expose check_url/check_urls as globals in your Twig environment for reusable logic:

    // config/view.php
    'globals' => [
        'check_url' => null,
        'check_urls' => [],
    ],
    
  • Testing: Mock the checkRoles tag in PHPUnit:

    $twig = new \Twig\Environment($loader);
    $twig->addExtension(new \Dcylabs\TwigBundle\Twig\Extension\CheckRolesExtension());
    $this->assertTemplateString('{% checkRoles "/test" %}OK{% endcheckRoles %}', 'OK');
    

Gotchas and Tips

Pitfalls

  1. Laravel-Symfony Mismatch:

    • The bundle is Symfony-focused. In Laravel, ensure:
      • Routes are properly matched (use Route::get() paths, not URIs).
      • The Symfony Security component is available (Laravel 5.5+ includes it via symfony/security-bundle).
    • Fix: Install symfony/security-core if missing:
      composer require symfony/security-core
      
  2. Path Matching Strictness: The bundle may use exact path matching. For Laravel’s route model binding or dynamic segments (e.g., /user/{id}), pre-process paths:

    {% checkRoles app.path('/admin') %}  {# Use Laravel's path() helper #}
    
  3. No Laravel-Specific Features:

    • No built-in support for Laravel’s can() method or policies.
    • Workaround: Create a custom Twig extension to bridge the gap:
      // app/Extensions/CustomCheckRolesExtension.php
      class CustomCheckRolesExtension extends \Twig\Extension\AbstractExtension
      {
          public function getFunctions()
          {
              return [
                  new \Twig\TwigFunction('laravelCheckRoles', [$this, 'checkLaravelRoles']),
              ];
          }
      
          public function checkLaravelRoles($paths)
          {
              // Implement Laravel-specific logic
          }
      }
      
  4. Dev Dependency Limitation: The package is installed as dev-master. Ensure your composer.json locks the version to avoid runtime issues:

    "require": {
        "dcylabs/symfony-twig-helper": "dev-master as 1.0.0"
    }
    

Debugging Tips

  1. Check Security Context: Dump the current user’s roles/permissions in Twig:

    {{ dump(app.user) if app.user is defined }}
    
  2. Override Twig Extension: Debug the checkRoles logic by extending the bundle’s Twig extension:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $twig = $this->app['view']->getEngine();
        $twig->addExtension(new class extends \Dcylabs\TwigBundle\Twig\Extension\CheckRolesExtension {
            public function checkRoles($paths)
            {
                // Add debug logs
                \Log::debug('Checking paths:', $paths);
                return parent::checkRoles($paths);
            }
        });
    }
    
  3. Route Paths: Verify paths match Laravel’s route generation:

    // In a test or Tinker
    route('admin.dashboard'); // Outputs: "/admin/dashboard"
    

Extension Points

  1. Custom Role Provider: Override the security context provider:

    // config/services.php
    'dcylabs.twig.helper.security.context' => function () {
        return new \YourApp\CustomSecurityContext();
    };
    
  2. Add New Twig Tags: Extend the bundle’s Twig extension to add custom tags:

    // app/Extensions/MyTwigExtension.php
    class MyTwigExtension extends \Twig\Extension\AbstractExtension
    {
        public function getTokenParsers()
        {
            return [new \YourApp\Twig\TokenParser\CustomCheckParser()];
        }
    }
    
  3. Path Normalization: Pre-process paths in a middleware to ensure consistency:

    // app/Http/Middleware/NormalizePaths.php
    public function handle($request, Closure $next)
    {
        $request->merge([
            'normalized_path' => Str::of($request->path())->lower()->trim('/'),
        ]);
        return $next($request);
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui