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

Inlinestyle Laravel Package

codeat3/inlinestyle

InlineStyle converts embedded/external CSS into inline style attributes on HTML elements—ideal for HTML emails where clients ignore stylesheets. Load HTML from a file or string, extract/apply stylesheets (with optional base URL), then get the modified HTML.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require codeat3/inlinestyle
    

    Add the service provider to config/app.php:

    Codeat3\Inlinestyle\InlinestyleServiceProvider::class,
    
  2. First Use Case: Inline CSS from a <style> block in a Blade template:

    @inlineStyle('<style>body { color: red; }</style>')
    <div>Hello, world!</div>
    

    Outputs:

    <div style="color: red;">Hello, world!</div>
    
  3. Alternative: Process HTML Strings:

    use Codeat3\Inlinestyle\InlineStyle;
    
    $html = '<style>p { margin: 0; }</style><p>Test</p>';
    $processor = new InlineStyle($html);
    $processor->applyStylesheet($processor->extractStylesheets());
    echo $processor->getHTML();
    

Implementation Patterns

Core Workflows

  1. Blade Integration:

    • Use @inlineStyle() for embedded CSS:
      @inlineStyle(file_get_contents('css/email-template.css'))
      
    • Chain multiple stylesheets:
      @inlineStyle('<style>body { font-family: Arial; }</style>')
      @inlineStyle('<style>a { color: blue; }</style>')
      
  2. Dynamic Email Templates:

    • Inline CSS for Mailable classes:
      public function build()
      {
          $html = view('emails.welcome')->render();
          $processor = new InlineStyle($html);
          $processor->applyStylesheet($processor->extractStylesheets());
          return $this->markdown('emails.welcome')
                      ->with(['html' => $processor->getHTML()]);
      }
      
  3. External Stylesheets:

    • Resolve relative URLs with a base path:
      $html = file_get_contents('https://example.com');
      $processor = new InlineStyle($html);
      $processor->applyStylesheet($processor->extractStylesheets(null, 'https://example.com'));
      
  4. Livewire/Alpine.js Integration:

    • Dynamically update styles in reactive components:
      public function mount()
      {
          $this->html = '<style>div { transition: all 0.3s; }</style><div>Hover me</div>';
      }
      

Laravel-Specific Patterns

  1. Service Provider Bootstrapping:

    • Register a facade for cleaner Blade usage:
      // InlinestyleServiceProvider.php
      public function boot()
      {
          Blade::directive('inlineStyle', function ($expression) {
              return "<?php echo (new \\Codeat3\\Inlinestyle\\InlineStyle($expression))->applyStylesheet((new \\Codeat3\\Inlinestyle\\InlineStyle($expression))->extractStylesheets())->getHTML(); ?>";
          });
      }
      
  2. Cached Inlining:

    • Cache processed HTML to avoid reprocessing:
      $cachedKey = 'inline_css_' . md5($html);
      return Cache::remember($cachedKey, 60, function () use ($html) {
          $processor = new InlineStyle($html);
          return $processor->applyStylesheet($processor->extractStylesheets())->getHTML();
      });
      
  3. Queue Jobs for Heavy Processing:

    • Offload CSS inlining to a queue for large templates (e.g., PDF generation):
      InlineCssJob::dispatch($html)->onConnection('database');
      

Gotchas and Tips

Pitfalls

  1. CSS Specificity Conflicts:

    • Inlined styles override external stylesheets. Test with:
      /* External CSS */
      .button { background: red; }
      /* Inlined CSS */
      <button style="background: blue !important;">Click</button>
      
    • Fix: Use !important sparingly or audit CSS cascades.
  2. Malformed HTML:

    • The package may fail silently on invalid HTML. Validate input:
      try {
          $processor = new InlineStyle($html);
      } catch (\Exception $e) {
          Log::error("Invalid HTML: " . $e->getMessage());
          return back()->withError('Template error');
      }
      
  3. Base URL Resolution:

    • Incorrect base URLs break external stylesheet fetching:
      // Wrong: Relative path without base URL
      $processor->extractStylesheets(null, 'https://example.com');
      // Right: Absolute URL
      $processor->extractStylesheets(null, 'https://example.com/assets/css');
      
  4. Performance:

    • Inlining large CSS files increases memory usage. Benchmark with:
      php -dmemory_limit=256M artisan your:command
      

Debugging Tips

  1. Inspect Processed HTML:

    • Log the output to debug:
      file_put_contents('debug.html', $processor->getHTML());
      
  2. Check Extracted Stylesheets:

    • Verify stylesheets are parsed correctly:
      $stylesheets = $processor->extractStylesheets();
      dd($stylesheets); // Debug extracted CSS
      
  3. Symfony Dependency Conflicts:

    • Resolve version conflicts with:
      composer why symfony/dom
      composer require symfony/dom:^6.4
      

Extension Points

  1. Custom Style Processing:

    • Override the applyStylesheet method to filter styles:
      class CustomInlineStyle extends \Codeat3\Inlinestyle\InlineStyle
      {
          public function applyStylesheet($stylesheets)
          {
              $filtered = array_filter($stylesheets, fn($css) => strpos($css, '.hidden') === false);
              return parent::applyStylesheet($filtered);
          }
      }
      
  2. Blade Directive Extensions:

    • Add support for file-based stylesheets:
      Blade::directive('inlineStyleFile', function ($expression) {
          return "<?php echo (new \\Codeat3\\Inlinestyle\\InlineStyle(file_get_contents($expression)))->applyStylesheet((new \\Codeat3\\Inlinestyle\\InlineStyle(file_get_contents($expression)))->extractStylesheets())->getHTML(); ?>";
      });
      
      Usage:
      @inlineStyleFile('css/email.css')
      
  3. Whitelist Tags/Attributes:

    • Restrict inlining to specific tags (e.g., avoid <script>):
      $processor = new InlineStyle($html);
      $processor->setAllowedTags(['div', 'p', 'a']); // Whitelist
      $processor->applyStylesheet($processor->extractStylesheets());
      

Config Quirks

  1. No Built-in Config:

    • The package lacks a publishable config file. Use environment variables or a custom service provider to manage settings:
      // config/inlinestyle.php
      return [
          'allowed_tags' => ['div', 'p', 'a', 'span'],
          'debug' => env('INLINE_STYLE_DEBUG', false),
      ];
      
  2. Symfony 7+ Compatibility:

    • Ensure your composer.json pins Symfony components to avoid conflicts:
      "require": {
          "symfony/dom": "^6.4",
          "symfony/css-selector": "^6.4"
      }
      

Pro Tips

  1. Pair with Tailwind:

    • Use @apply in inlined CSS for utility-first workflows:
      @inlineStyle('<style>@import "tailwind.css"; .btn { @apply px-4 py-2 bg-blue-500; }</style>')
      <button class="btn">Click</button>
      
  2. Email-Specific Optimizations:

    • Inline critical CSS for email clients:
      $emailHtml = view('emails.welcome')->render();
      $processor = new InlineStyle($emailHtml);
      $processor->applyStylesheet($processor->extractStylesheets());
      $processor->setAllowedTags(['table', 'td', 'tr', 'a']); // Email-safe tags
      
  3. Livewire Dynamic Styles:

    • Update inlined styles reactively:
      public $color = 'red';
      public function mount()
      {
          $this->html = '<style>div { color: ' . $this->color . '; }</style><div>Dynamic</div>';
      }
      public function updateColor($color)
      {
          $this->color = $color;
          $this->html = '<style>div { color: ' . $this->color . '; }</style>' . $this->html;
      }
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor