Mitech Preloader
Magento / Magento2

How to add Image in knockout html template file in Magento 2?

add images in knockout html template file

If you want to add a dynamic image from the theme or module’s web/images folder, You can be assigned images using the knockout template with ease.
Simply call the function in src of your image tag, require.toUrl(‘web/images’)
Keep the image in web/images/logo.png location of your theme or module.

Now simply add one line in .html template to display the image on your page.

<img data-bind="attr: { src: require.toUrl('images/logo.png') }" />

Using this method, Your images search for the theme web/images folder.

If you want to display Images from specific Module’s Web folder:

If you have images in the module web folder in your theme or Custom module,
app/design/frontend/{Vendor}/{themename}/Magento_Checkout/web/images/logo.png

You have to add module name before image path,

<img data-bind="attr: { src: require.toUrl('Magento_Checkout/images/logo.png') }" />

When you see the front page, your images have taken a path from the pub/static folder.

This is the simple way to show images in the knockout .html template.

You can also get the custom or base URL of the store in the KnockoutJS inside .html file for the frontend area.
Using the below code snippet, You can fetch the store required page URL inside .html(web/template) file.

checkout.baseUrl
checkout.checkoutUrl
checkout.customerLoginUrl
checkout.removeItemUrl
checkout.shoppingCartUrl
checkout.updateItemQtyUrl

checkoutConfig.cartUrl
checkoutConfig.checkoutUrl
checkoutConfig.defaultSuccessPageUrl
checkoutConfig.forgotPasswordUrl
checkoutConfig.pageNotFoundUrl
checkoutConfig.registerUrl
checkoutConfig.staticBaseUrl

Using “checkout.baseUrl”, You will get the baseUrl mentioned below.

<a class="action viewcart hompgeurl" data-bind="attr: {href: checkout.baseUrl}"><img data-bind="attr: { src: require.toUrl('images/left-arrow.png') }" /></a>

 

blank