Hello, community members! I would like to ask you this question: In the Yii2 framework, to use css styles and js scripts, you need to set a so-called resource bundle so that the application can use them. And what to do with the images? I do not understand how to access their use ..

This is what is meant by the resource bundle:

class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', 'css/bootstrap.min.css', 'css/bootstrap-social-gh-pages/bootstrap-social.css', 'css/flexslider.css', 'css/ie10-viewport-bug-workaround.css', 'css/justified-nav.css', 'css/font-awesome-4.6.3/css/font-awesome.css', ]; public $js = [ 'scripts/ie-emulation-modes-warning.js', 'scripts/jquery.flexslider-min.js', 'scripts/modernizr.js', 'https://code.jquery.com/jquery.min.js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js' ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; } 
  • And what image do you need to show? Can you just put it on the site and display it via a direct link, will this option work? - cronfy
  • I need to show an image that should be in some web application directory. Accessing an image directly results in an access error. - Zimovik007
  • And if you put the image in the same folder as index.php, will there be an access error? - cronfy Nov.

1 answer 1

In fact, resource bundles in Yii2 are not for publishing images =) However, it is possible to publish the internal directory through public $ sourcePath and then use the image in a relative way, but this is not for your case.

You have two options.

1) Putting images on the web. And then just use the relative path src = "/ example.jpg"

2) Store images wherever and wherever you like and give them through the controller action. For example, a site action controller of some type

 public function actionDownload($id) { $image = ImageModel::findOne($id); $filePath = Yii::$app->imageComponent->getFileDirPath($image->hash) . DIRECTORY_SEPARATOR . $image->hash . '.' . $image->type; return \Yii::$app->response->sendFile($filePath, "$image->name.$image->type"); } 

of course, you need to write the imageComponent component yourself .. and for good you need to provide for the generation of thumbnails in it .. respectively, the path to the picture will be src = "/ site / download? id = 7"

... I suspect there is little knowledge, probably you should use ready-made extensions like https://github.com/CostaRico/yii2-images