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

Plates Laravel Package

league/plates

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require league/plates

Add to composer.json if using Laravel's autoloader:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "League\\Plates\\": "vendor/league/plates/src/"
    }
}
  1. Basic Usage: Create a template file (resources/views/hello.php):

    <h1><?= $name ?></h1>
    

    Render it in a controller:

    use League\Plates\Engine;
    
    $loader = new \League\Plates\Engine('resources/views');
    echo $loader->render('hello', ['name' => 'World']);
    
  2. Laravel Integration: Create a service provider (app/Providers/PlatesServiceProvider.php):

    use League\Plates\Engine;
    use Illuminate\Support\ServiceProvider;
    
    class PlatesServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton('plates', function ($app) {
                return new Engine($app['path.base'].'/resources/views');
            });
        }
    }
    

    Register in config/app.php:

    'providers' => [
        // ...
        App\Providers\PlatesServiceProvider::class,
    ],
    

Implementation Patterns

Core Workflows

1. Template Inheritance & Layouts

Use layouts for consistent UI across pages:

// resources/views/layouts/default.php
<!DOCTYPE html>
<html>
<head>
    <title><?= $title ?></title>
</head>
<body>
    <?= $content ?>
</body>
</html>

Extend in child templates:

// resources/views/home.php
<?php $this->layout('layouts/default') ?>
<?php $this->start('title') ?>
    Home Page
<?php $this->stop() ?>
<h1>Welcome!</h1>

2. Sections & Content Blocks

Define reusable sections:

// resources/views/partials/nav.php
<nav>
    <?php $this->start('nav_items') ?>
    <?php $this->stop() ?>
</nav>

Extend in parent templates:

<?php $this->start('nav_items') ?>
    <a href="/">Home</a>
    <a href="/about">About</a>
<?php $this->stop() ?>

3. Dynamic Data Binding

Preassign data globally or per-template:

$loader = new Engine('resources/views');
$loader->setData(['site_name' => 'MyApp']); // Global data
echo $loader->render('home', ['page_title' => 'Dashboard']);

4. Extensions for Reusability

Create custom extensions (e.g., app/Extensions/UrlHelper.php):

use League\Plates\Extension\ExtensionInterface;

class UrlHelper implements ExtensionInterface {
    public function register(Engine $engine) {
        $engine->registerFunction('url', function ($path) {
            return route($path);
        });
    }
}

Register in your service provider:

$engine->loadExtensions([
    new App\Extensions\UrlHelper()
]);

Use in templates:

<a href="<?= url('home') ?>">Home</a>

5. Themes & Fallback Folders

Organize templates by theme (e.g., resources/views/themes/dark/):

$loader = new Engine('resources/views');
$loader->setFolder('themes/dark'); // Set active theme
$loader->addFolder('themes/light', 'light'); // Fallback theme

6. Asset Management

Use the asset() helper (included in Plates):

<img src="<?= asset('images/logo.png') ?>" alt="Logo">

Laravel-Specific Patterns

1. View Composers

Replace Laravel's view composers:

$loader->addFolder('composers', 'composers');
$loader->setData(['user' => auth()->user()]); // Global auth data

2. Blade-Like Directives

Extend Plates to mimic Blade syntax:

$engine->registerFunction('if', function ($condition, $content) {
    if ($condition) echo $content;
});

Usage:

@if($show_header)
    <header>...</header>
@endif

3. Service Container Integration

Bind Plates to Laravel's container:

$this->app->bind('plates', function ($app) {
    $engine = new Engine($app['path.base'].'/resources/views');
    $engine->loadExtensions([
        new App\Extensions\UrlHelper(),
        new App\Extensions\AuthHelper(),
    ]);
    return $engine;
});

4. Middleware for Template Data

Attach data in middleware:

public function handle($request, Closure $next) {
    $plates = app('plates');
    $plates->setData(['user' => auth()->user()]);
    return $next($request);
}

5. Caching Templates

Cache compiled templates (Laravel 8+):

$engine = new Engine('resources/views', 'storage/framework/views');

Gotchas and Tips

Common Pitfalls

1. Template Paths & Case Sensitivity

  • Issue: resources/views/Home.php fails to render if called as home.php.
  • Fix: Use strtolower() or configure case-insensitive paths:
    $engine = new Engine('resources/views', 'storage/framework/views', [
        'fileExtension' => 'php',
        'cache' => true,
        'autoReload' => true,
    ]);
    

2. Section Content Leaks

  • Issue: Unclosed sections spill content into other blocks.
  • Fix: Always pair start() with stop():
    <?php $this->start('sidebar') ?>
        <!-- Content -->
    <?php $this->stop() ?>
    

3. Data Overwriting

  • Issue: Per-template data overwrites global data unexpectedly.
  • Fix: Use mergeData() to combine data:
    $engine->mergeData(['global_key' => 'global_value']);
    echo $engine->render('template', ['local_key' => 'local_value']);
    

4. Extensions Not Loading

  • Issue: Custom extensions fail silently.
  • Fix: Verify registration order and engine instance:
    $engine->loadExtensions([new MyExtension()]);
    $engine->registerFunction('my_func', function() { ... }); // Alternative
    

5. Output Buffering Conflicts

  • Issue: ob_start() interferes with Plates rendering.
  • Fix: Disable buffering or use toString():
    $template = $engine->make('template');
    $content = $template->toString(); // Bypass output buffering
    

6. PHP 8.1+ Deprecations

  • Issue: Dynamic properties or callable type hints break.
  • Fix: Update to Plates v3.5+ and use strict types:
    public function register(Engine $engine): void { ... }
    

Debugging Tips

1. Template Existence Check

if ($engine->exists('template')) {
    echo $engine->render('template');
} else {
    throw new \RuntimeException("Template not found");
}

2. Inspect Template Data

$template = $engine->make('template');
dump($template->data()); // Debug all available data

3. Enable Auto-Reload

$engine = new Engine('views', 'cache', [
    'autoReload' => true, // For development
]);

4. Custom Error Handling

Override error handling in your service provider:

$engine->setErrorHandler(function ($error) {
    Log::error($error);
    abort(500, 'Template Error');
});

Performance Tips

1. Cache Compiled Templates

$engine = new Engine('resources/views', 'storage/framework/views', [
    'cache' => true,
]);

2. Preload Extensions

Register extensions once during bootstrapping (not per-request).

3. Avoid Deep Nesting

Limit nested templates/

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