简体   繁体   中英

adding attributes Html::img yii2

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 class="item">
    <?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?

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM