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

Tools for dynamic server-side HTML generation: rich set of tag classes, custom tags, widgets (ButtonGroup, CheckboxList, RadioList), automatic HTML-encoding with NoEncode bypass, and an Html helper with static methods to build tags and widgets.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**:
   ```bash
   composer require yiisoft/html

Add to composer.json if using Laravel:

"require": {
    "yiisoft/html": "^1.0"
}
  1. First Use Case: Generate a simple link in a Laravel Blade template:

    <?= \Yiisoft\Html\Html::a('Click Me', '/dashboard') ?>
    

    Outputs: <a href="/dashboard">Click Me</a>

  2. Key Entry Points:

    • Tag Objects: Yiisoft\Html\Tag\* (e.g., Div, A, Form).
    • Helper Methods: Static Html::* methods (e.g., Html::button(), Html::form()).
    • Widgets: ButtonGroup, CheckboxList, RadioList.

Implementation Patterns

1. Tag Object Workflow

  • Fluent Interface: Chain methods for attributes/content:
    $link = (new \Yiisoft\Html\Tag\A())
        ->href('/profile')
        ->class('btn btn-primary')
        ->content('Profile');
    echo $link; // Renders HTML
    
  • Nested Tags: Build complex structures:
    $card = (new \Yiisoft\Html\Tag\Div())
        ->class('card')
        ->content(
            (new \Yiisoft\Html\Tag\H2())->content('Title'),
            (new \Yiisoft\Html\Tag\P())->content('Content')
        );
    

2. Helper Methods for Quick Use

  • Static Convenience:
    // Button
    echo \Yiisoft\Html\Html::button('Submit', ['type' => 'submit']);
    
    // Form
    echo \Yiisoft\Html\Html::form(['action' => '/submit']);
    
  • Form Inputs:
    echo \Yiisoft\Html\Html::textInput('username', 'John Doe');
    echo \Yiisoft\Html::checkbox('agree', true, ['label' => 'Agree']);
    

3. Widgets for Complex UI

  • Button Groups:
    $group = (new \Yiisoft\Html\Widget\ButtonGroup())
        ->buttons(
            \Yiisoft\Html\Html::submitButton('Save'),
            \Yiisoft\Html\Html::resetButton('Cancel')
        )
        ->containerAttributes(['class' => 'btn-group']);
    
  • Checkbox/Radio Lists:
    $list = (new \Yiisoft\Html\Widget\CheckboxList\CheckboxList('colors'))
        ->items(['red' => 'Red', 'blue' => 'Blue'])
        ->value(['red']);
    

4. Integration with Laravel

  • Blade Directives: Create custom Blade directives for reusable components:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('yiiform', function ($input) {
        return "<?= \\Yiisoft\\Html\\Html::form($input); ?>";
    });
    

    Usage in Blade:

    @yiiform(['action' => '/submit'])
    
  • Form Requests: Use yiisoft/html to generate form inputs dynamically:

    public function buildForm(array $data, FormInterface $form) {
        $form->add('name', \Yiisoft\Html\Html::textInput('name', $data['name']));
    }
    

5. Dynamic Content Handling

  • NoEncode for Raw HTML:
    use Yiisoft\Html\NoEncode;
    echo \Yiisoft\Html\Html::div(NoEncode::string('<b>Bold Text</b>'));
    
  • Conditional Rendering:
    $alert = $errors ? (new \Yiisoft\Html\Tag\Div())
        ->class('alert alert-danger')
        ->content(implode('<br>', $errors))
        : null;
    echo $alert ?? '';
    

Gotchas and Tips

1. Encoding Pitfalls

  • Default Behavior: All string content is auto-encoded unless wrapped in NoEncode or a tag object.
    // Encoded: &lt;script&gt;alert('XSS')&lt;/script&gt;
    echo \Yiisoft\Html\Html::div('<script>alert("XSS")</script>');
    
    // Not Encoded: <script>alert('XSS')</script>
    echo \Yiisoft\Html\Html::div(NoEncode::string('<script>alert("XSS")</script>'));
    
  • Tag Objects: Nested tag objects are not encoded by default:
    echo \Yiisoft\Html\Html::div(\Yiisoft\Html\Html::b('Bold')); // <div><b>Bold</b></div>
    

2. ID Generation in Tests

  • Non-Deterministic IDs: By default, IDs include a timestamp (e.g., i1685000000000).
    • Disable for Tests:
      require_once 'vendor/yiisoft/html/src/test-functions.php';
      \Yiisoft\Html\IdGenerator\disableSeed();
      
    • Reset Counter:
      \Yiisoft\Html\IdGenerator\reset(); // Next ID: i1
      

3. Attribute Handling

  • Boolean Attributes: Use true/false for boolean attributes (e.g., disabled):
    echo \Yiisoft\Html\Html::input('text', 'disabled', ['disabled' => true]);
    
  • Data Attributes: Prefix with data- or use the data method:
    echo \Yiisoft\Html\Html::div(['data-user-id' => 123]);
    // OR
    echo (new \Yiisoft\Html\Tag\Div())->data('user-id', 123);
    

4. Performance Tips

  • Reuse Tag Objects: Instantiate tags once and reuse them (e.g., in loops):
    $link = new \Yiisoft\Html\Tag\A();
    foreach ($items as $item) {
        $link->href('/item/' . $item->id)->content($item->name);
        echo $link;
    }
    
  • Avoid Redundant Renders: Call render() only when needed (e.g., in Blade templates).

5. Custom Tags and Extensions

  • Extend for Domain-Specific Tags:
    class Card extends \Yiisoft\Html\Tag\Div {
        public function header(string $content): self {
            return $this->content(new \Yiisoft\Html\Tag\H2($content));
        }
    }
    
  • Override Encoding: Extend \Yiisoft\Html\Tag\Tag to customize encoding:
    class SafeTag extends \Yiisoft\Html\Tag\Tag {
        public function encode($content): string {
            return $content; // Never encode
        }
    }
    

6. Debugging

  • Inspect Rendered HTML: Use ->render() to debug tag content:
    $tag = (new \Yiisoft\Html\Tag\Div())->content('Test');
    dd($tag->render()); // Debug output
    
  • Check Attributes: Use getAttributes() to inspect attributes:
    $button = \Yiisoft\Html\Html::button('Click');
    dd($button->getAttributes()); // ['type' => 'button']
    

7. Laravel-Specific Quirks

  • Blade vs. PHP: Blade auto-escapes output, so disable encoding if needed:
    {!! \Yiisoft\Html\Html::div('<b>Raw</b>')->encode(false) !!}
    
  • Asset URLs: Use Laravel’s asset() helper for local files:
    echo \Yiisoft\Html\Html::cssFile(asset('css/app.css'));
    

8. Common Mistakes

  • Forgetting to Render: Tag objects must be cast to string or called with render():
    $tag = new \Yiisoft\Html\Tag\Div(); // Not rendered yet!
    echo $tag; // Works (type cast)
    // OR
    echo $tag->render();
    
  • Overriding Attributes: Use ->attribute() instead of ->setAttribute() for clarity:
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