Magento 2 frontend Knockout code
In this tutorial I show you how Magento 2 frontend Knockout code works. You may have seen this Knockout codes in some of Magento 2 html template files and wondered how this works. I show you all you need to know about that.
Magento 2 frontend Knockout code
If you are new to Magento 2 you may have wondered why there are commented out code snipets in some html frontend files. They are all use this <!– ko –> and basically look like php script tags in phtml files from Magento 1. Magento 1 frontend is build entirely with MVC pattern, Magento 2 uses a newer concept which is called MVVM pattern – an advanced MVC pattern approach. It is implemented in Knockoutjs, a JavaScript library for simplifying dynamic JS UIs.
By example
Learning by example is the right choice for new things, so create a new module and a file called
1 | app/code/COMPANYNAME/MODULENAME/view/frontend/web/js/example.js |
you need to replace COMPANYNAME and MODULENAME with your desired strings. Copy past following code for your first view model:
1 2 3 4 5 6 7 8 | define(['uiComponent'], function(Component) { return Component.extend({ initialize: function () { this._super(); this.output = "Hello world!"; } }); }); |
Not very interesting, but this view model will print out classic “Hello world!” example string. As you can see, out view model depends on uiComponent (see Magento_Ui/js/lib/core/collection.js) which itself is inherited from uiElement (see Magento_Ui/js/lib/core/element/element.js) where Knockout code is implemented.
Next we create our view with following sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <div data-bind="scope: 'example'"> <!-- ko template: getTemplate() --><!-- /ko --> </div> <script type="text/x-magento-init"> { "*": { "Magento_Ui/js/core/app": { "components": { "koexample": { "component": "Inchoo_Js/js/example", "template" : "Inchoo_Js/example" } } } } } </script> |
As component we define our example.js model view and template is example.html. You need to create this file with following content too:
1 2 | <p>I am template located on: app/code/Inchoo/Js/view/frontend/web/template/example.html and dynamically loaded. This is my message to you:</p> <p data-bind="text: output"></p> |
Now it is time to test our code. Start a browser and past an URL to your created example view. You will see, that it is displayed with dynamically inserted output code. Your static html template displays now dynamically loaded content by JavaScript code. It is easy to change that by expanding example.js and you do not need to change your template. It is possible to use this template on different sites, you only need to use different JS code.
Conclusion
With Knockout code it is possible to create dynamic content for static html files. It is a new technique used by Magento 2 to create a kind of templating system for frontend code.