How to Use KnockoutJS Foreach in Magento 2
Knockout JS is a Javascript library that allows you to create dynamic interfaces and implements the MVVM(Model-View-View Model) pattern to bind data to certain DOM elements.
You can find KnockoutJS almost on every page, but the checkout page is the place where Knockout is used the most.
Although applying KnockoutJS is one of the most tricky and complicated tasks in Magento 2 for developers, it makes your code more powerful as it allows you to add a great deal of seamless functionality to your store.
The foreach binding duplicates a section of markup for each entry in an array and binds each copy of that markup to the corresponding array item.
For instance, if you want to add more than one custom rate with different titles in the sidebar of the cart page. In that scenario, you have to use knockoutJS foreach in Magento 2.
Use the below example to learn the KnockoutJS foreach.
Method to Use KnockoutJS Foreach in Magento 2:
- Use the below code in your .html file.
12345678<!-- ko foreach: { data: getDetails(), as: 'item' } --><tr class="totals sub"><th data-bind="text: item.id" class="mark" scope="row"></th><td class="amount"><span class="price" data-bind="text: item.price"></span></td></tr><!-- /ko --> - Use the below code in your .js file.
12345678910111213141516171819202122232425define(['ko','jquery','uiComponent','Magento_Checkout/js/model/quote'], function(ko, $, Component, quote) {'use strict';return Component.extend({getDetails: function() {array allItem = [{id : '1',price : '120'},{id : '2',price : '150'}];return allItem;}});});
Use this solution wherever you need to use knockoutJs foreach loop.
That’s it!
Any doubts about this solution can be mentioned in the Comments section below.
I’d be happy to help.
Also, do share the post with Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Move Related Products Above Product Tabs in Magento 2
How to Encrypt and Decrypt URL Parameter in Magento 2
Next