Magento – Magento 2 knockout js in checkout page

javascriptknockoutjsmagento2template

I want to customize checkout page but i am confused about calling template with knockout js. In Magento/Checkout/view/frontend/templates/onepage.phtml there is a script like this:

<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
{
    "#checkout": {
        "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
    }
}
</script>

What is the meaning of this script?

Best Answer

TL:DR

The template it calls is magento/module-checkout/view/frontend/web/template/onepage.html.

My research is below.

What does this script do?

"#checkout": {
    "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
}

This informs Magento to call the JS layout if the #checkout element exists on the page.


<!-- ko template: getTemplate() --><!-- /ko -->

The above code tells Magento to render a template, now how does it know which template to render? If you look at the parent div you'll see this code:

data-bind="scope:'checkout'"

This is informing Magento that the nested code is in relation of the checkout (it does more than this but I'm not going too far into it).


Find the template

The template can be defined within the text/x-magento-init tag, but Magento don't usually do it this way as you can see. Magento usually do it via the XML method, which is what this line does:

$block->getJsLayout();

This gets the components configuration from the XML, so let's take a look at that.


If you search vendor/magento/module-checkout/view/frontend/layout for onepage.phtml it should return magento/module-checkout/view/frontend/layout/checkout_index_index.xml. So let's look in here for the config.

Nested within checkout.root you will see a lot of <argument> tags, if you look at this line - <item name="checkout" xsi:type="array"> this relates to the scope we saw earlier. Within this there is a line that defines a template:

<item name="template" xsi:type="string">Magento_Checkout/onepage</item>

So this means the getTemplate() call is returning:

magento/module-checkout/view/frontend/web/template/onepage.html

As you can tell by the XML file UI components can be pretty overwhelming, there is also a lot more that I've left out it could go on forever and I don't have a good understanding of all aspects yet. But hopefully this points you in the right direction.

Related Topic