I want to display an image in the module template file. When somebody installs my module, he can see that image. Can I store my images inside my module directory or not?

  • Ohoo ankush bhai magento2 – Amit Singh Jan 5 '17 at 10:16

Yes you can store images in your module web directories depending on the area of your templates. The path is: Vendor/Module/view/{frontend|adminhtml}/web/images/

Then in your *.phtml files you can display the image:

<img src="<?php echo $this->getViewFileUrl('Vendor_Module::images/image.png'); ?>" />
  • If I want that url in helper how can I get it? or in js file ? – Nitesh Feb 6 '17 at 11:48
  • In helper you can inject \Magento\Framework\View\Result\PageFactory class in your constructor as $pageFactory and then call $pageFactory->getViewFileUrl() method. For js files I have no idea how you can get it. – Miroslav Petroff Feb 6 '17 at 14:28

I like to base-64 encode my PNG's and inline them. I use https://www.base64-image.de.

        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJ....=">
<script type="text/x-magento-init">
    <?php /* this defines the target of the widget */ ?>
    "#target_id": {
        <?php /* this defines the widget */ ?>
        "image.widget.name": {
            "imagename" : "<?php echo $this->getViewFileUrl('Vendor_Module::images/image.png'); ?>"

You would use magento's widget initialization script to start your javascript with the "imagename" option defined. This initialization technique is typically done in phtml files. My code assumes your image is in Vendor/Module/view/{frontend|adminhtml}/web/images/

For more information, you can see the magento 2 documentation. http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/javascript/js_init.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.