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

Html Laravel Package

berry/html

Build HTML templates directly in PHP with a fluent, type-safe element builder. Compose tags, attributes, classes, and children, then render to string. Great for minimal templating and dynamic UI patterns (e.g., HTMX) without context switching.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require berry/html
    

    Requires PHP 8.3+.

  2. First Use Case Create a simple HTML element chain:

    use Berry\Html\Element;
    
    echo div()->text('Hello, Berry!')->toString();
    

    Outputs:

    <div>Hello, Berry!</div>
    
  3. Where to Look First

    • Core Classes: Berry\Html\Element, Berry\Html\Tag, and Berry\Html\Rel (for link relations).
    • Examples: The README’s counterButton and layout functions demonstrate common patterns.
    • API Docs: Use IDE autocompletion (e.g., div()->attr()) or generate PHPDoc-based docs with phpDocumentor.

Implementation Patterns

1. Declarative HTML Construction

Workflow: Build components as reusable functions returning Element objects.

function card(string $title, string $content): Element {
    return div()
        ->class('card')
        ->child(header()->child(h2()->text($title)))
        ->child(div()->child(p()->text($content)));
}

Integration Tip: Use dependency injection (e.g., Laravel’s service container) to pass shared elements (e.g., headers/footers).


2. Dynamic Attributes and Conditional Rendering

Pattern: Leverage PHP logic to conditionally add attributes or children.

function userCard(array $user): Element {
    return div()
        ->class('user-card ' . ($user['active'] ? 'active' : ''))
        ->attr('data-id', $user['id'])
        ->child(avatar()->src($user['avatar'] ?? null));
}

Tip: Use ->when(bool $condition, callable $callback) for complex logic:

div()->when($user['admin'], fn($el) => $el->class('admin'));

3. HTMX/Livewire Integration

Example: Combine with HTMX for dynamic updates (as in the README):

button()
    ->attr('hx-post', '/update')
    ->attr('hx-swap', 'outerHTML')
    ->text('Update');

Tip: Pair with berry/htmx for type-safe HTMX helpers.


4. Laravel-Specific Patterns

Blade-Like Templates: Replace Blade with Berry in views:

// routes/web.php
Route::get('/dashboard', fn() => view('dashboard', ['user' => $user]));

// resources/views/dashboard.php
echo layout(
    main()->child(userProfile($user))
);

Tip: Use Laravel’s View::make() to render Berry components:

return View::make('component', ['data' => $data])->render();

5. Component Composition

Pattern: Nest components hierarchically.

function page(Element $content): Element {
    return html()
        ->child(head()->child(title()->text('My Page')))
        ->child(body()->child($content));
}

echo page(
    div()->child(h1()->text('Welcome'))
);

Gotchas and Tips

Pitfalls

  1. Strict Typing:

    • Methods like text() or attr() may throw TypeError if arguments don’t match expected types (e.g., passing null to text()).
    • Fix: Use assert() or is_string() checks:
      $title = $user['title'] ?? 'Untitled';
      assert(is_string($title));
      h1()->text($title);
      
  2. Attribute Ordering:

    • Berry preserves attribute order (unlike Laravel’s Html::attributes()). If order matters (e.g., for CSS specificity), manually chain attributes:
      div()->class('base')->class('modifier'); // Order preserved
      
  3. Self-Closing Tags:

    • Tags like <img> or <input> require explicit selfClosing():
      img()->src('/image.jpg')->selfClosing();
      

Debugging Tips

  1. Inspect Elements: Use ->toString() to debug rendered output:

    echo div()->child(p()->text('Debug'))->toString();
    
  2. PHPStan: The package includes PHPStan rules. Run:

    composer require --dev phpstan/phpstan
    vendor/bin/phpstan analyse src
    
  3. HTMX Debugging: For HTMX issues, inspect the hx-* attributes and ensure the server responds with valid HTML fragments.


Extension Points

  1. Custom Tags: Extend Berry\Html\Tag to add domain-specific tags:

    class MyTag extends Tag {
        public static function create(): self { return new self('my-tag'); }
    }
    // Usage: MyTag::create()->attr('data-x', '123');
    
  2. Global Modifiers: Create a base Element wrapper to add shared attributes:

    function baseElement(Element $el): Element {
        return $el->attr('data-app', 'berry');
    }
    // Usage: baseElement(div()->text('Hello'));
    
  3. Laravel Service Provider: Bind Berry’s Element factory to Laravel’s container:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(Element::class, fn() => div());
    }
    

Config Quirks

  • No Config File: Berry is zero-config. All behavior is runtime-driven via method chaining.
  • Namespace Collisions: Avoid naming conflicts with Laravel’s Html facade by aliasing:
    use Berry\Html\Element as BerryElement;
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon