Alternate UI Component JSON syntax

In this lesson, we will go over the alternate UI Component JSON syntax. To start, view the source of the current page using the Command Option U shortcut. Search for free shipping banner. Next, we will examine the value of x-magento-init.

Copy Value to Clipboard

Take the value passed to js/core/app and copy it to the clipboard. Return to the IDE and open up the free-shipping-banner.phtml file. Replace the contents of getJsLayout with what was copied to the clipboard. Reformat the code so it’s easier to understand by removing the escaped backslashes and adding line breaks.

JSON vs XML

It is important to note that we do not have to use XML to configure our UI Components; we can simply use JSON. Comparing the layout XML to the JSON output, you can see there is a direct relation between the two. The readability of JSON is much easier compared to XML, making it simpler to follow.

getJsLayout is converted into a JavaScript object and passed to app. This app file expects a list of components, merges all of these files together in one giant tree structure, and then instantiates all of the components afterwards.

When to Use JSON Format

You might wonder why we showed the XML format compared to the much easier to read JSON syntax. The reason is that XML is much more extensible. By defining the configuration in XML, you allow any third-party module to easily extend and override any of these values. This is especially important if you are coding a third-party module or need any sort of extensibility. XML is the format Magento uses in most of their core code, providing much more flexibility over JSON syntax.

However, if your custom code only applies to locally installed modules, such as for a specific store instance, you can use the JSON syntax. Keep in mind that it is not very extensible, but it is easier to read and diagnose what’s going on. Personally, we recommend using the XML format for most cases.

Using Xdebug

Let’s also look at this from another perspective by using Xdebug. Open the debug panel by typing Ctrl D. Set a breakpoint at the block->getJsLayout line. After refreshing the page, the breakpoint should catch. Expand the debug panel and add a call to block->getJsLayout. The output should be the JSON that was found before.

By inspecting the jsLayout array, you can see how the assignments match up to the XSI types defined in XML.

Now you have an understanding of how everything works with jsLayout and the alternate UI Component JSON syntax.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock