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

yiisoft/html

yiisoft/html is a lightweight PHP HTML builder for generating safe, well-formed markup. Create tags, attributes, forms, and input elements with fluent helpers, automatic escaping, and convenient utilities—ideal for Yii and any PHP project needing clean HTML generation.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require yiisoft/html
    

    No additional configuration is required—it’s a standalone library.

  2. First Use Case: Basic HTML Generation Import the core classes and start building HTML:

    use Yiisoft\Html\Html;
    use Yiisoft\Html\HtmlTag;
    
    // Generate a simple link
    $link = Html::tag('a', 'Click me', ['href' => '/example']);
    echo $link; // Output: <a href="/example">Click me</a>
    
  3. Key Entry Points

    • Html::tag(): Core method for creating HTML tags.
    • Html::encode(): Safely escape dynamic content.
    • Html::activeForm(): For form generation (if using Yii integration).
    • Predefined helpers like Html::a(), Html::img(), etc.
  4. Where to Look First

    • Source Code (if available) for advanced usage.
    • Yii Framework Docs (if used in Yii context).
    • Method signatures in Yiisoft\Html\Html for available helpers.

Implementation Patterns

1. Tag Generation Workflow

  • Dynamic Tags:
    $userId = 123;
    $editLink = Html::a('Edit', ['/users/edit', 'id' => $userId]);
    
  • Nested Tags:
    $div = Html::tag('div', [
        Html::tag('h1', 'Title'),
        Html::tag('p', 'Content'),
    ], ['class' => 'container']);
    
  • Self-Closing Tags:
    $img = Html::tag('img', null, ['src' => '/image.jpg', 'alt' => 'Image']);
    

2. Form Handling (Yii Integration)

If using in a Yii project, leverage Html::activeForm() for model binding:

use Yiisoft\Yii\Web\View;

$form = Html::activeForm(['model' => $user]);
echo $form->field($user, 'username')->textInput();
echo Html::submitButton('Save');
$form->end();

3. Content Encoding

Always encode dynamic content to prevent XSS:

$userInput = '<script>alert("XSS")</script>';
$safeInput = Html::encode($userInput);
// Output: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

4. Custom Attributes and Data Attributes

Use the [] syntax for attributes:

$button = Html::tag('button', 'Submit', [
    'type' => 'submit',
    'data' => ['action' => 'save', 'confirm' => 'Are you sure?'],
]);

5. Integration with Blade (Laravel)

Create a helper file (e.g., app/Helpers/html.php):

if (!function_exists('html_tag')) {
    function html_tag(string $tag, ?string $content = null, array $options = []): string {
        return \Yiisoft\Html\Html::tag($tag, $content, $options);
    }
}

Then use it in Blade:

{!! html_tag('div', 'Hello', ['class' => 'alert']) !!}

6. Reusable Components

Encapsulate complex HTML in closures or classes:

function card(string $title, string $content): string {
    return Html::tag('div', [
        Html::tag('h3', $title),
        Html::tag('p', $content),
    ], ['class' => 'card']);
}

Gotchas and Tips

1. Pitfalls

  • Double Encoding: Avoid double-encoding when mixing Html::encode() with Laravel’s e() or Blade’s {!! !!}:
    // ❌ Wrong (double-encoded)
    echo Html::encode(e($userInput));
    
    // ✅ Correct
    echo e(Html::encode($userInput));
    
  • HTML Fragment Handling: Html::tag() expects a single string or array of tags for content. Passing raw HTML fragments may break rendering:
    // ❌ May fail if $html contains unescaped tags
    Html::tag('div', $html);
    
    // ✅ Safer
    Html::tag('div', Html::encode($html));
    
  • Yii-Specific Assumptions: Some methods (e.g., Html::activeForm()) assume Yii’s request/response objects. In Laravel, mock these or use standalone alternatives.

2. Debugging Tips

  • Inspect Output: Use var_dump() or dd() to verify tag structure before rendering:
    $tag = Html::tag('div', 'Test');
    var_dump($tag); // Debug the raw HTML
    
  • Check for Missing Attributes: Typos in attribute names (e.g., href vs. herf) will silently fail. Validate with:
    $attributes = ['href' => '/test', 'herf' => '/fallback'];
    $link = Html::tag('a', 'Link', $attributes);
    // Only 'href' will render; 'herf' is ignored.
    
  • Browser DevTools: Use the browser’s inspector to compare expected vs. actual HTML output.

3. Configuration Quirks

  • No Global Config: Unlike Yii, this package has no global configuration. All settings are passed via method arguments.
  • Encoding Defaults: Html::encode() uses htmlspecialchars() with ENT_QUOTES and UTF-8. Override if needed:
    $customEncoded = htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'ISO-8859-1');
    

4. Extension Points

  • Custom Tag Helpers: Extend the library by creating wrapper functions:
    function button(string $label, array $options = []): string {
        return Html::tag('button', $label, $options);
    }
    
  • Attribute Sanitization: Add validation for attributes (e.g., reject onclick for security):
    function sanitizeAttributes(array $attributes): array {
        unset($attributes['onclick'], $attributes['onload']);
        return $attributes;
    }
    $safeTag = Html::tag('div', null, sanitizeAttributes($attrs));
    
  • Integration with Laravel Collectives: Bridge with Laravel Collective’s HTML helpers for consistency:
    function laravelLink(string $title, string $url, array $attributes = []): string {
        return Html::a($title, $url, $attributes);
    }
    

5. Performance Tips

  • Cache Complex HTML: Generate reusable components once and cache them:
    $navbar = Html::tag('nav', [
        Html::tag('ul', [
            Html::tag('li', Html::a('Home', '/')),
            Html::tag('li', Html::a('About', '/about')),
        ]),
    ]);
    
  • Avoid Redundant Encoding: Encode dynamic content once before passing to Html::tag():
    // ❌ Inefficient
    Html::tag('div', Html::encode($userInput));
    
    // ✅ Efficient
    $safeInput = Html::encode($userInput);
    Html::tag('div', $safeInput);
    

6. Laravel-Specific Notes

  • Blade vs. PHP Mixing: Use {!! !!} for raw HTML output from Html::tag() to avoid Blade auto-escaping:
    {!! Html::tag('div', 'Raw HTML') !!}
    
  • Asset Management: Combine with Laravel Mix/Vite for asset paths:
    $img = Html::tag('img', null, [
        'src' => asset('images/logo.png'),
        'alt' => 'Logo',
    ]);
    
  • Form Requests: Use Laravel’s old() helper with Html::activeForm() for persistence:
    echo Html::activeTextInput($user, 'email', ['value' => old('email')]);
    
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