Home > Back-end >  adding attributes Html::img yii2
adding attributes Html::img yii2

Time:08-04

I add images to the page, to which I add some attributes

<?php

$data = [
    [
        'data-z-index' => 1,
        'data-width'   => 300,
    ]
];

?>

<?php foreach ($posts as $i => $item) { ?>
  <div >
    <?php if ($item->img) { ?>
      <?= Html::img($item->img->getUrl(), $data[$i]) ?>
    <?php } ?>
  </div>
<?php } ?>

As a result, on the page all this works for me and I get

<img src="//test.loc/storage/posts-image/1-2.jpg" alt="" data-z-index="1" data-width="300">

Now I also want to add an alt attribute that will come from the database

<?= Html::img($item->img->getUrl(), [$data[$i], 'alt' => $item->img_alt]) ?>

But now the attribute formatting is changing and 0 appears at the beginning

<img src="//test.loc/storage/posts-image/1-2.jpg" alt="post1" 0-data-z-index="1" 0-data-width="300">

What could be the problem?

CodePudding user response:

It's because $data is an array. So you have a nested array as options.

Try to merge the arrays:

array_merge($data[$i], ['alt' => $item->img_alt]);
  • Related