yiiyii3

Should the order I do the method chaining affect the output when using yiisoft/html to generate HTML?


Should the order I do the method chaining affect the output when using yiisoft/html to generate HTML? Only the $c example seems to do what I expect.

Does the documentation point out that the order you write these matters?

composer.json

{
    "require": {
        "yiisoft/html": "^3.11"
    }
}

index.php

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';

use Yiisoft\Html\Tag\Div;

$a = Div::tag()
    ->id('id-a')
    ->class('my-class')
    ->attributes(['tabindex' => '-1'])
    ->content('My A Content')
    ->render();

$b = Div::tag()
    ->id('id-b')
    ->attributes(['tabindex' => '-1'])
    ->class('my-class')
    ->content('My B Content')
    ->render();

$c = Div::tag()
    ->attributes(['tabindex' => '-1'])
    ->id('id-c')
    ->class('my-class')
    ->content('My C Content')
    ->render();

echo $a . $b . $c;

Outputs:

<div tabindex="-1">My A Content</div>
<div class="my-class" tabindex="-1">My B Content</div>
<div id="id-c" class="my-class" tabindex="-1">My C Content</div>

Solution

  • I realised that I was using attributes(), but if I replace with addAttributes() it preserves the id & class.