简体   繁体   English

添加属性 Html::img yii2

[英]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现在我还想添加一个来自数据库的 alt 属性

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

But now the attribute formatting is changing and 0 appears at the beginning但是现在属性格式正在改变,开头出现0

<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.这是因为$data是一个数组。 So you have a nested array as options.所以你有一个嵌套数组作为选项。

Try to merge the arrays:尝试合并 arrays:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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