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

Laravel Blade Laravel Package

spatie/laravel-blade

Add Blade to any PHP project with the standalone Blade engine from Spatie. Compile and render Blade templates outside Laravel, with an easy API, caching support, and configurable view paths—ideal for small apps, packages, or custom tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-blade
    

    Add the service provider to config/app.php:

    Spatie\Blade\BladeServiceProvider::class,
    
  2. First Use Case: Compile a Blade template to a string:

    use Spatie\Blade\Facades\Blade;
    
    $compiled = Blade::render('path.to.view', ['data' => 'value']);
    
  3. Key Files:

    • vendor/spatie/laravel-blade/src/Blade.php (Core class)
    • vendor/spatie/blade/src/Facades/Blade.php (Facade for easy access)
    • config/blade.php (Configuration, if any)

Implementation Patterns

Core Workflows

  1. Standalone Blade Rendering: Use Blade outside Laravel’s request lifecycle (e.g., CLI scripts, APIs, or non-Laravel PHP apps):

    $html = Blade::render('emails.welcome', ['user' => $user]);
    
  2. Dynamic View Resolution: Resolve views dynamically with custom logic:

    $viewPath = $user->prefersDarkMode ? 'dark.layout' : 'light.layout';
    Blade::render($viewPath, ['user' => $user]);
    
  3. Component Registration: Register custom Blade components globally:

    Blade::component('alert', AlertComponent::class);
    

    Use in templates:

    @alert('Success!', 'type="success"')
    
  4. Directives: Create custom directives for reusable logic:

    Blade::directive('datetime', function ($expression) {
        return "<?php echo ($expression)->format('Y-m-d H:i'); ?>";
    });
    

    Use in templates:

    @datetime($post->created_at)
    
  5. Integration with Non-Laravel Apps: Use Blade to generate HTML in standalone PHP apps by injecting the Blade compiler:

    $blade = new \Spatie\Blade\Blade();
    $blade->addViewPath(__DIR__.'/views');
    $html = $blade->render('home', ['title' => 'Hello']);
    

Best Practices

  • Caching: Disable caching during development (Blade::setCachePath(null)).
  • View Paths: Register multiple view paths for modular projects:
    Blade::addViewPath(__DIR__.'/resources/views');
    Blade::addViewPath(__DIR__.'/vendor/package/views');
    
  • Error Handling: Wrap Blade calls in try-catch for graceful failures:
    try {
        $html = Blade::render('view');
    } catch (\Exception $e) {
        log::error($e->getMessage());
        return 'Fallback HTML';
    }
    

Gotchas and Tips

Common Pitfalls

  1. Missing View Paths:

    • Issue: View [path] not found.
    • Fix: Ensure paths are registered with Blade::addViewPath().
    • Tip: Use absolute paths for clarity.
  2. Directive Scope:

    • Issue: Custom directives not working.
    • Fix: Register directives before rendering:
      Blade::directive('foo', function () { ... });
      Blade::render('view'); // Now works
      
  3. Caching Quirks:

    • Issue: Changes to Blade templates not reflected.
    • Fix: Clear cache (Blade::clearCompiled()) or disable caching in development.
  4. Component Autoloading:

    • Issue: @component tags failing with "Class not found".
    • Fix: Ensure components are registered before rendering or use anonymous classes:
      Blade::component('alert', function ($slot) {
          return "<div class='alert'>$slot</div>";
      });
      
  5. Namespace Collisions:

    • Issue: Blade templates not found due to namespace conflicts.
    • Fix: Use fully qualified paths or alias namespaces in composer.json:
      "autoload": {
          "psr-4": {
              "App\\": "app/",
              "Views\\": "resources/views/"
          }
      }
      

Debugging Tips

  • Enable Debug Mode:
    Blade::setDebugMode(true); // Shows raw Blade errors
    
  • Inspect Compiled Output:
    $compiled = Blade::render('view');
    file_put_contents('debug.blade.php', $compiled);
    
  • Log View Paths:
    $paths = Blade::getViewPaths();
    log::debug('Blade view paths:', $paths);
    

Extension Points

  1. Custom Compilers: Extend \Spatie\Blade\Blade to modify compilation logic:

    class CustomBlade extends \Spatie\Blade\Blade {
        public function compile($value) {
            // Pre-process templates
            return parent::compile($value);
        }
    }
    
  2. Event Hooks: Listen for Blade events (if supported in future versions) or wrap calls in middleware:

    Blade::render($view, $data); // Trigger custom logic before/after
    
  3. Integration with Blade Directives: Use existing directives (e.g., @stack, @push) for layout management in non-Laravel contexts.

Configuration Quirks

  • No Config File: The package relies on method chaining (e.g., Blade::addViewPath()) rather than a config/blade.php file.
  • Global State: Blade maintains state (e.g., view paths, directives) globally. Reset state between uses if needed:
    $blade = new \Spatie\Blade\Blade();
    $blade->addViewPath('/new/path');
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport