Answers:
使用以下代码获取图像网址 view
<img src="<?php echo $this->getViewFileUrl('Vendor_Module::images/image.png'); ?>" />
更新:
<?php echo $block->getViewFileUrl('images/demo.jpg'); ?>
要在助手或控制器中获取图像路径,您需要使用
use Magento\Framework\View\Asset\Repository;
use Magento\Framework\App\RequestInterface; // for $this->request
在您的文件中。
添加存储库并创建对象assetRepo
&之后request
,使用函数调用图像路径,
$params = array('_secure' => $this->request->isSecure());
$this->assetRepo->getUrlWithParams('Nitesh_Module::images/image.png', $params);
参考vendor\magento\module-payment\Model\CcConfig.php::getViewFileUrl($fileId, array $params = [])
功能
编辑
为了获得安装脚本,API调用和Cronjobs的正确图像路径,您将需要添加如下所示的仿真以获得正确的图像路径。
public function __construct(
\Magento\Framework\View\Asset\Repository $assetRepo,
\Magento\Framework\App\RequestInterface $request,
\Magento\Store\Model\App\Emulation $appEmulation
)
{
$this->assetRepo = $assetRepo;
$this->request = $request;
$this->appEmulation = $appEmulation;
}
public FunctionName($param){
$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
$params = array('_secure' => $this->request->isSecure());
$this->assetRepo->getUrlWithParams('Nitesh_Module::images/image.png', $params);
$this->appEmulation->stopEnvironmentEmulation();
}