Weave 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

Hinclude Laravel Package

mnot/hinclude

Laravel package that adds Server Side Includes (hinclude) support, letting you compose pages from reusable fragments and render parts independently. Useful for micro-frontends, partial caching, and speeding up complex views by loading sections separately.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer

    composer require mnot/hinclude
    

    The package provides a PHP library for server-side processing of HTML Inclusion (HInclude) directives, which allows embedding external resources (like partials, ads, or analytics) declaratively in HTML.

  2. Basic Usage in Laravel Add middleware to process HInclude directives before rendering views:

    // app/Http/Kernel.php
    protected $middleware = [
        // ...
        \Mnot\Hinclude\Middleware::class,
    ];
    
  3. First Use Case: Embedding Partial Views In a Blade template (resources/views/layouts/master.blade.php):

    <!DOCTYPE html>
    <html>
    <head>
        <!-- Include analytics script -->
        <hinclude src="https://example.com/analytics.js" type="text/javascript">
    </head>
    <body>
        <!-- Include a reusable header -->
        <hinclude src="/partials/header.blade.php" type="text/html">
        @yield('content')
    </body>
    </html>
    

    The middleware will resolve and replace <hinclude> tags with their fetched content.


Implementation Patterns

1. Dynamic Inclusion Workflows

  • Conditional Inclusion Use hinclude with if attributes for dynamic loading:

    <hinclude src="/partials/ads.blade.php" if="user.is_premium">
    

    Laravel can pre-process this via middleware or Blade directives.

  • Caching Responses Cache fetched inclusions to avoid repeated HTTP requests:

    // In a custom middleware extending \Mnot\Hinclude\Middleware
    public function handle($request, Closure $next) {
        $response = $next($request);
        $response->headers->set('X-HInclude-Cache', 'true');
        return $response;
    }
    

2. Integration with Laravel Ecosystem

  • Blade Directives Extend Blade to support custom hinclude syntax:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('hinclude', function ($expression) {
        return "<?php echo app(\Mnot\Hinclude\Hinclude::class)->process($expression); ?>";
    });
    

    Usage:

    @hinclude('/partials/footer.blade.php')
    
  • API-Driven Inclusions Fetch inclusions from APIs (e.g., CMS or microservices):

    <hinclude src="https://api.example.com/content/header" type="application/json">
    

    Process JSON responses in middleware:

    // Custom middleware to decode JSON
    public function handle($request, Closure $next) {
        $response = $next($request);
        $content = json_decode($response->getContent(), true);
        return response()->make(view('partials.api', ['content' => $content]));
    }
    

3. Security Patterns

  • Whitelist Allowed Sources Restrict inclusions to trusted domains:

    // config/hinclude.php
    'allowed_domains' => [
        'example.com',
        'cdn.example.com',
    ],
    

    Add validation in middleware:

    if (!in_array(parse_url($src, PHP_URL_HOST), config('hinclude.allowed_domains'))) {
        throw new \Exception("Inclusion from untrusted domain: {$src}");
    }
    
  • CSRF Protection for Local Inclusions For local Blade partials, ensure CSRF tokens are included:

    <hinclude src="/partials/form.blade.php" csrf="true">
    

Gotchas and Tips

Pitfalls

  1. Circular Inclusions

    • Issue: A.hinclude includes B.hinclude, which includes A.hinclude → infinite loop.
    • Fix: Track included files in middleware and throw an error on cycles:
      private $includedFiles = [];
      public function handle($request, Closure $next) {
          if (in_array($request->path(), $this->includedFiles)) {
              throw new \Exception("Circular inclusion detected");
          }
          $this->includedFiles[] = $request->path();
          // ...
      }
      
  2. Performance Overhead

    • Issue: Excessive inclusions slow down rendering.
    • Fix: Use Laravel’s view()->share() to pre-load common inclusions or lazy-load with JavaScript.
  3. Type Mismatches

    • Issue: Fetching a text/html inclusion but getting application/json.
    • Fix: Validate type attributes and transform content in middleware:
      if ($type === 'application/json') {
          $content = json_decode($response->getContent(), true);
          return response()->make(view('json', ['data' => $content]));
      }
      

Debugging Tips

  • Log Inclusions Log resolved inclusions for debugging:

    // In middleware
    \Log::debug("HInclude resolved: {$src} -> " . substr($content, 0, 50));
    
  • Disable in Production Use environment-based toggling:

    // config/hinclude.php
    'enabled' => env('HINCLUDE_ENABLED', false),
    

Extension Points

  1. Custom Processors Extend \Mnot\Hinclude\Processor to handle non-HTTP sources (e.g., database):

    class DatabaseProcessor extends \Mnot\Hinclude\Processor {
        public function fetch($src) {
            return DB::table('partials')->where('slug', $src)->first()->content;
        }
    }
    
  2. Event Listeners Trigger events for inclusions (e.g., analytics):

    // app/Providers/EventServiceProvider.php
    \Event::listen('hinclude.fetched', function ($src, $content) {
        \Analytics::track('hinclude', ['src' => $src]);
    });
    
  3. Fallback Content Provide fallback HTML if inclusion fails:

    <hinclude src="/partials/sidebar.blade.php" fallback="<div>Fallback content</div]">
    
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.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route