-->

Yii2: how to display images from backend/web to fr

2019-09-09 12:08发布

问题:

I need to display 1 (first) image which path is saved in database like Img1.jpg;img2.jpg;, I tried to seperate each path by using explode, getting all the images as array but not able to pick single path-

<div class="col-sm-6 masonry-item">
<a href="<?php echo Url::to(['site/roompage']); ?>" class="product_item text-center">
<span class="product_photo bordered_wht_border">

<?php
foreach (explode(';',rtrim($row['images'],';'),1) as $key_img => $value_img)
{
?>

<?php echo  Html::img('@backend/web'.'/'.$value_img);?>                  

<?php
}
?>

</span>
<span class="product_title"><?php echo $row['room_type']; ?></span>
<span class="product_price">Rs.<?php echo $row['rate']; ?></span>

</a>
</div>
<?php endforeach; ?> 

回答1:

  <?php

    // if you want only the first image is better 
    $my_image  = explode(';',rtrim($row['images'],';'),1);
    echo  Html::img('@backend/web'.'/'.$my_image[0]);

    }
  ?>                 

otherwise

  <?php

    // if you want all the image  

    foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
    {
      echo  Html::img('@backend/web'.'/'.$value_img);
    }
  ?>  

this because (explode(';',rtrim($row['images'],';'),1) return an array of two element (the first and the rest)



回答2:

The src parameter, containing the backend alias, will be processed by Url::to()

Check the docs for details on Html::img()