Display a Knockout.js template from a UI Component
In our module’s visual mockup, the first block we need to create is a SKU Lookup block. This will be a text input field with a “Confirm SKU” button. Clicking that button will call the Magento API to confirm that the SKU exists and return the product name.
Building the SKU Lookup Block
To build the SKU Lookup block, let’s create a new
<div> with an ID of “sku-lookup” within the “shipping-plan”
<div> in the
shipping-plan.phtml file. Inside this
<div>, create a Knockout virtual element with a type of “template” and the value will be a
getTemplate() function call. Close up these tags, as well as the closing Knockout tag. After saving this file, the
getTemplate() will return null because the “template” property doesn’t yet exist on the UI Component.
Creating the Template Property
To create the “template” property, open up the layout XML file. Within the “sku-lookup” item, create another
<item> node with the name of “config”, which will have the “xsi:type” of “array”. Inside the
<config> array, create a new
<item> node with the name of “template”. When the call to
getTemplate() executes, this is the value that will be returned. This will have an “xsi:type” of “string”, and the value for this template will be a custom Magento string.
The custom Magento string consists of the vendor name and module name, followed by a slash and the name of the Knockout template file without any extension. In this case, the vendor and module name is “Macademy_InventoryFulfillment”, and the Knockout template file’s name is “sku-lookup”. The value after the slash is relative to the
Creating the Knockout Template File
Create a file named
template/sku-lookup.html. Note that Knockout templates go in a “template” folder and not a “templates” folder, which stores
.phtml files. For the contents of this file, create a new
<h2> tag and name it “sku-lookup”. Save the file and then go back to the
/inventory-fulfillment route & refresh. You should see the “SKU Lookup” header.
Loading the Knockout Template and View Model
Managing IDs and Classes
It’s important to note that the “id” attribute should be placed in the
.phtml file and not the Knockout template because there can only be one DOM element with a unique “id”. If the “id” is within the Knockout template, then it’s intended to be loaded only once. However, Knockout templates can be loaded many times if desired. This approach allows for multiple copies of the same template to be used on one page with unique “id”s.
It’s also a good idea to wrap Knockout templates in a container element. In this case, wrap the template within a
.phtml files allows for extensibility to either target a specific “id” or a specific “class” if needed.