Insert an image into a template

We just have some text here in this template override, but having an image on this page would be much nicer.

I grabbed this really cute & funny image of a dog wearing a Yoda costume, but you can basically grab any JPG, PNG or WEBP file that you want to do this lesson. I named this file yoda-dog.png, and made sure it wasn’t too big in size. We want to display an image to the user along with this notice message if no search terms are returned.

To display this file in our template, we can put it in one of two spots. Let’s go over the first place we can place it, and that is within the web/images of our theme. This is the place that we are putting our logo.

Next, we’ll use a special helper function to display this image. Below this h2 tag, let’s create a new img tag. The src attribute will be set to a short echo tag which calls a function of the parent block class. This will be $block->getViewFileUrl(). We’ll then pass it the location of our image, relative to the web directory of our theme, so this will be images/yoda-dog.png. We’ll also be sure to add an alt tag here to describe this image for accessibility reasons, and also pass this string through the translation function.

If we reload the page, we’ll now see this really cute dog when no search results are returned.

We did use the general web/images directory of our theme to store this image, but this is only good for images that could be potentially used in many different areas of our theme as they are more global in nature. I don’t expect this Yoda dog image to be used anywhere other than in this specific place, so let’s move it somewhere that is more organized.

Since this template is overriding a template from the Magento_CatalogSearch module, this is also a good place to store this image. We can create a web/images directory within this module directory of our theme. Then, move the file over there.

To update our code to look for this location, we just need to prefix our image location with that special string format of the module that it is located in, followed by two colons. So we will prefix it with Magento_CatalogSearch::.

This is a more organized place to store this specific image, and it makes a bit more sense to me to store this image here.

And when we reload the page, we’ll see that it still displays this image properly.

Before we move on to LESS & styling, there’s one more thing we need to know: how to add the parent class to a custom page layout.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock